Order a string row based on another string row by matching each element (like the sort function does)
13 次查看(过去 30 天)
显示 更早的评论
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 个评论
回答(1 个)
James Tursa
2020-5-1
编辑:James Tursa
2020-5-1
One way:
[~,idxb] = sort(B1);
[~,idxa] = sort(idxb);
A1new = A1(idxa);
A2new = A2(idxa);
3 个评论
James Tursa
2020-5-1
编辑:James Tursa
2020-5-1
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);
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Shifting and Sorting Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!