Order a string row based on another string row by matching each element (like the sort function does)
11 views (last 30 days)
Show older comments
I have two string rows with each cell containing "M#" where # is a number. I want to order one of them based on the other one and then be able to order another matrix based on the changes the first one underwent. Like when you can use the indexes of [~,index]=sort(A).
To be completely clear. I have A1=["M1" "M2" ... "M12"] and another one B1=["M10" "M5" "M1" ...] where the order of B1 is unknown to me and it is the outcome of other manipulations. A1 contains the titles of each column of another matrix A2. So I want to reorder A1 to match B1 and then reorder A2 in the same manner so that the strings correspond to the right columns.
Thanks in advance.
0 Comments
Answers (1)
James Tursa
on 1 May 2020
Edited: James Tursa
on 1 May 2020
One way:
[~,idxb] = sort(B1);
[~,idxa] = sort(idxb);
A1new = A1(idxa);
A2new = A2(idxa);
3 Comments
James Tursa
on 1 May 2020
Edited: James Tursa
on 1 May 2020
This does not sort the B1 vector. Did you try it? This reorders the A1 and A2 vectors to match the current B1 ordering, which is what I thought you asked.
It does have a caveat, though. It uses the sort( ) function string ordering. Maybe this is what you need if the strings in B1 match the strings in A1:
[~,idxa] = ismember(B1,A1);
A1new = A1(idxa); % but this is the same result as A1new = B1
A2new = A2(idxa);
See Also
Categories
Find more on Shifting and Sorting Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!