calcposition.m 987 B

123456789101112131415161718192021222324252627282930313233343536
  1. function f = calcposition(list,x)
  2. % function f = calcposition(list,x)
  3. %
  4. % <list> is a vector with unique elements (must be positive integers)
  5. % <x> is a vector whose elements are in <list>.
  6. % elements can be in any order and repeats are okay.
  7. %
  8. % return a vector the same length as <x> with indices relative to <list>.
  9. %
  10. % example:
  11. % isequal(calcposition([5 3 2 4],[2 2 5]),[3 3 1])
  12. % construct a vector that gives the correct index for X if you extract the Xth element
  13. xrank = NaN*zeros(1,max(list)); % if max(list) is big, this is ouch
  14. xrank(list) = 1:length(list);
  15. % get the answers
  16. f = xrank(x);
  17. % sanity check
  18. assert(~any(isnan(f)),'<list> does not subsume <x>');
  19. % NICER, BUT SLOWER:
  20. % % init
  21. % f = zeros(size(x));
  22. % % do it
  23. % xu = union(x,[]);
  24. % for p=1:length(xu)
  25. % temp = find(list==xu(p));
  26. % assert(~isempty(temp),'<list> does not subsume <x>');
  27. % f(x==xu(p)) = temp; % POTENTIALLY SLOW. see commented code below for a faster but less general solution
  28. % end