Getting largest to lowest values from a row
Ältere Kommentare anzeigen
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...
Antworten (2)
Roger Stafford
am 16 Feb. 2015
Let A be your original matrix.
B = [sort(A(2,:),'descend');sort(A(3,:),'ascend')];
B = B(:);
3 Kommentare
rod schola
am 16 Feb. 2015
Roger Stafford
am 16 Feb. 2015
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
am 17 Feb. 2015
Image Analyst
am 16 Feb. 2015
0 Stimmen
Do a loop over rows, then call sort(). Alternate between 'ascend' and 'descend' options.
4 Kommentare
rod schola
am 16 Feb. 2015
Image Analyst
am 16 Feb. 2015
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
am 16 Feb. 2015
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
am 17 Feb. 2015
Kategorien
Mehr zu Matrix Indexing finden Sie in Hilfe-Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!