Order a string row based on another string row by matching each element (like the sort function does)

11 views (last 30 days)
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.

Answers (1)

James Tursa
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
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);
Paraskevas Theologitis
Paraskevas Theologitis on 1 May 2020
I tried out the [~,idxb] = sort(B1); line but it sorted the strings is B1 vector, which I dont want it to do.
Nevermind, I came up with a workaround. I used the position index of each value in B1 as a number given to each matching string to vector A1. That means if "M20" was in position B1(1,4) and the same string in vector A1 was in positon A1(1,10) then in a new vector i stored the above as workaround(1,10)=4. Then I procedded to sort the workaround vector in ascending order and with the indexes from calling [~,idx]=sort(workaround,'ascend') I sorted the matrix I wanted to. The code I wrote has a little bit more stuff in it as it is variable-dependent and that is the reason I am not posting it.
Thanks for trying to help though.

Sign in to comment.

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!