Swapping the elements in a matrix
Show older comments
Hi everyone, I have a matrix :
[0.8 0.7 0.9 0.5;0.6 0.4 0.9 0.7;0.8 0.5 0.6 0.5;0.8 0.6 0.5 0.4]
I want to write a nested for loop to swap the minimum element and maximum element of two direct rows until the minimum element in each row is greater than or equal to maximum element in the subsequent row. Such that the final matrix looks like this:
[0.8 0.8 0.9 0.9;0.7 0.8 0.6 0.7;0.6 0.6 0.5 0.5;0.5 0.4 0.5 0.4]
Thanks
2 Comments
James Tursa
on 28 Aug 2017
Edited: James Tursa
on 28 Aug 2017
What is your definition of "two direct rows"? I.e., exactly which rows are being compared for the swapping?
Also, the location of the numbers in the end result is going to depend on the order in which you do the row comparisons. So you will need to specify precisely how you want this done. E.g., you could compare two rows and do swapping on them until they met the criteria, and then move on. Or you could do only one swap and move on. In either case coming back to them later to see if there are any additional swaps that must be done. You will get different final answers depending on what order you do the row comparisons, and depending on which elements get swapped if there is more than one min or max in the row.
Peterikye
on 28 Aug 2017
Accepted Answer
More Answers (1)
Andrei Bobrov
on 28 Aug 2017
Edited: Andrei Bobrov
on 28 Aug 2017
A = [0.8 0.7 0.9 0.5;0.6 0.4 0.9 0.7;0.8 0.5 0.6 0.5;0.8 0.6 0.5 0.4];
n = size(A,1);
for ii = rem(0:(n-1)^(n-1)-1,n-1)+1
[v1,k1] = min(A(ii,:));
[v2,k2] = max(A(ii+1,:));
if v1 < v2
t = A(ii,k1);
A(ii,k1) = A(ii+1,k2);
A(ii+1,k2) = t;
end
end
Categories
Find more on Loops and Conditional Statements 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!