qbetween.m 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. function [y,xi]=qbetween(x, start, finish,refs)
  2. % y=between(x, start, finish)
  3. % returns the values of x that are between start and finish
  4. % if start and finish are vectors y is a cell array
  5. % works for sorted 1D vectors.
  6. % using find you get o(n) , by assuming that the vector is sorted you get
  7. % 2*o(log(n)). which is WAY better.
  8. if nargin==3
  9. refs=zeros(size(start));
  10. end
  11. if numel(start)>1
  12. for sx=1:numel(start)
  13. [y{sx} xi{sx}]=stats.qbetween(x,start(sx), finish(sx), refs(sx));
  14. end
  15. else
  16. if isempty(x) || (x(end)<start) || x(1)>finish || isnan(start) || isnan(finish)
  17. y=[]; xi=[];
  18. return
  19. end
  20. i=stats.qfind(x, [start finish]);
  21. %qfind returns -1 if the target is less than min(x), since we are
  22. %getting 'between', we just take the first relevant x
  23. if i(1)>i(2)
  24. y=[]; xi=[];
  25. return
  26. elseif i(1)==0
  27. i(1)=1;
  28. end
  29. %this code deals with the fact that if there is no exact match, qfind
  30. %will return the index that is one lower than the target. since we
  31. %want between, we just double check the end points. every other point
  32. %will be valid.
  33. y=x(i(1):i(2));
  34. xi=i(1):i(2);
  35. if y(1)<start
  36. y=y(2:end);
  37. xi=xi(2:end);
  38. end
  39. if isempty(y)
  40. y = [];
  41. xi = [];
  42. return;
  43. end
  44. if y(end)>finish
  45. y=y(1:end-1);
  46. xi=xi(1:end-1);
  47. end
  48. y=y-refs;
  49. end