What I would like to do is make a matrix such as 'A = [8,9,5;15,10,17];' and put the first row into ascending order. However I would also like the second row to be place into the same order. So I would like an output of 'A = [5,8,9;17,10,15];'. How can I execute this in MATLAB? Thanks in advance.
CodePudding user response:
You're looking to use functionality of the sort function.
From the MathWorks website:
B = sort(A)
B = sort(A,dim)
B = sort(___,direction)
B = sort(___,Name,Value)
[B,I] = sort(___)
The first return argument is the sorted list and the second is the indices of the sorted list. These can be used to shuffle another list in the same way the original input was sorted. This will be applied to you second row after sorting on the first row.
A = [8,9,5;15,10,17];
[B, I] = sort(A(1, :)); % defaults to ascending order
A(1, :) = B;
A(2, :) = A(2, I); % "shuffle" the second row to match the sorting order
