spm_match_str.m 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. function [sel1, sel2] = spm_match_str(a, b)
  2. % MATCH_STR looks for matching labels in two listst of strings
  3. % and returns the indices into both the 1st and 2nd list of the matches.
  4. % They will be ordered according to the first input argument.
  5. %
  6. % [sel1, sel2] = match_str(strlist1, strlist2)
  7. %
  8. % The strings can be stored as a char matrix or as an vertical array of
  9. % cells, the matching is done for each row.
  10. %_______________________________________________________________________
  11. % Copyright (C) 2000, Robert Oostenveld
  12. % Robert Oostenveld
  13. % $Id: spm_match_str.m 3589 2009-11-20 17:17:41Z guillaume $
  14. % ensure that both are cell-arrays
  15. if isempty(a)
  16. a = {};
  17. elseif ~iscell(a)
  18. a = cellstr(a);
  19. end
  20. if isempty(b)
  21. b = {};
  22. elseif ~iscell(b)
  23. b = cellstr(b);
  24. end
  25. % ensure that both are column vectors
  26. a = a(:);
  27. b = b(:);
  28. % regardless of what optimizations are implemented, the code should remain
  29. % functionally compatible to the original, which is
  30. % for i=1:length(a)
  31. % for j=1:length(b)
  32. % if strcmp(a(i),b(j))
  33. % sel1 = [sel1; i];
  34. % sel2 = [sel2; j];
  35. % end
  36. % end
  37. % end
  38. % replace all unique strings by a unique number and use the fact that
  39. % numeric comparisons are much faster than string comparisons
  40. [dum1, dum2, c] = unique([a; b]);
  41. a = c(1:length(a));
  42. b = c((length(a)+1):end);
  43. sel1 = [];
  44. sel2 = [];
  45. for i=1:length(a)
  46. % s = find(strcmp(a(i), b)); % for string comparison
  47. s = find(a(i)==b); % for numeric comparison
  48. sel1 = [sel1; repmat(i, size(s))];
  49. sel2 = [sel2; s];
  50. end