Swapping the elements in a matrix
古いコメントを表示
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 件のコメント
James Tursa
2017 年 8 月 28 日
編集済み: James Tursa
2017 年 8 月 28 日
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
2017 年 8 月 28 日
採用された回答
その他の回答 (1 件)
Andrei Bobrov
2017 年 8 月 28 日
編集済み: Andrei Bobrov
2017 年 8 月 28 日
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
カテゴリ
ヘルプ センター および File Exchange で Loops and Conditional Statements についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!