MATLAB: How to keep ordering of found indices when using contains

containsfind

Hi Everyone,
I have a cell array called "data" containing a field "data.labels". In addition to that I have the cell "lbls" containing label strings and I would like to find the indices of elements in data.labels that contain lbls.
Using
idx = find(contains(data.labes,lbls));
is doing the job but returns the indices sorted in ascending order. How can I keep the original ordering of the indices?
Thanks in advance and all best,
M.

Best Answer

It's not being sorted, it's returning the matches that are found globally just like you asked it to do, not by individual elements in the searching-for array. The contains operation is completed, then that result is passed to find. The locations in the label array are where they are; there's no way to know which of the elements it was that was the one found at any given location; that's not what you asked for.
If you want them returned individually, you'll have to do the search for the elements in lbls one at a time; don't think of any way to differentiate which match is which, otherwise.
Example (modified from cotains documentation):
str = ["Anne","Elizabeth","Marianne","Tracy"]; % sample data; struct is immaterial to problem
pattern = "anne"; % find one location
TF = find(contains(str,pattern,'IgnoreCase',true));
TF =
1 3
returns the two locations expected...nothing to see here, really.
pattern = ["anne";"liz"]; % now find more than one element
TF=find(contains(str,pattern,'IgnoreCase',true));
find(TF)
TF =
1 2 3
Again, it finds then all but the '2' is for 'Elizabeth'. Nothing was sorted, per se, just that as noted, the search is global.
str(end+1)=str(2); str(2)=[] % rearrange to put lizzie at the end...
str =
1×4 string array
"Anne" "Marianne" "Tracy" "Elizabeth"
TF = find(contains(str,pattern,'IgnoreCase',true))
TF =
1 2 4
To find individual locations that can keep track of who,
>> TF=arrayfun(@(pattern) find(contains(str,pattern,'IgnoreCase',true)),pattern,'uni',0)
TF =
2×1 cell array
{1×2 double}
{[ 4]}
>> TF{:}
ans =
1 2
ans =
4