Getting largest to lowest values from a row
이전 댓글 표시
Hi, I have a matrix with 3 rows and 10 columns. I would like to use a loop to get the largest value of the second row first, then the lowest of the third row, then again largest value of the second but excluding the one previously selected. To summarize, I have this matrix [1 2 3 4 5 6 7 8 9 10; 5 6 7 8 9 10 11 12 13; 2 5 6 5 7 8 9 3 4 0] and I would like to use a loop to take 13 from second row first, then 0 from third, then 12 from the second row, then 2 from the third, etc...
답변 (2개)
Roger Stafford
2015년 2월 16일
Let A be your original matrix.
B = [sort(A(2,:),'descend');sort(A(3,:),'ascend')];
B = B(:);
댓글 수: 3
rod schola
2015년 2월 16일
Roger Stafford
2015년 2월 16일
That's what this code does! Have you tried it out? I tried it on your example and it produces:
B = [13;0;12;2;11;3;10;4;9;5;8;5;7;6;6;7;5;8;4;9]
just as you requested. (Note: I inserted a 4 in front of your second line because that line had only nine elements, and that 4 appears next to last in the twenty elements of B.)
rod schola
2015년 2월 17일
Image Analyst
2015년 2월 16일
0 개 추천
Do a loop over rows, then call sort(). Alternate between 'ascend' and 'descend' options.
댓글 수: 4
rod schola
2015년 2월 16일
Image Analyst
2015년 2월 16일
Try this:
clc;
m = [1 2 3 4 5 6 7 8 9 10;
5 6 7 8 9 10 11 12 13 0;
2 5 6 5 7 8 9 3 4 0]
[rows, columns] = size(m)
output = m; % Initialize
for row = 2 : rows
if rem(row, 2) == 0
% Row is even. Sort row with largest number first.
output(row, :) = sort(m(row, :), 'descend');
else
% Row is odd. Sort row with smallest number first.
output(row, :) = sort(m(row, :), 'ascend');
end
end
% Print to command window:
output
Or if you're certain you have only 3 rows, use Roger's code.
Image Analyst
2015년 2월 16일
Or if you just want a column vector with the mins and maxes, that would be output(:,1) of the above code, or you can use this code to give a vector output instead of an array where you keep and sort all the elements:
clc;
m = [1 2 3 4 5 6 7 8 9 10;
5 6 7 8 9 10 11 12 13 0;
2 5 6 5 7 8 9 3 4 0]
[rows, columns] = size(m)
output = m(1,1); % Initialize
for row = 2 : rows
if rem(row, 2) == 0
% Row is even. Sort row with largest number first.
output(row) = max(m(row, :));
else
% Row is odd. Sort row with smallest number first.
output(row) = min(m(row, :));
end
end
% Print to command window:
output
rod schola
2015년 2월 17일
카테고리
도움말 센터 및 File Exchange에서 Matrix Indexing에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!