Getting largest to lowest values from a row
2 views (last 30 days)
Show older comments
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...
0 Comments
Answers (2)
Roger Stafford
on 16 Feb 2015
Let A be your original matrix.
B = [sort(A(2,:),'descend');sort(A(3,:),'ascend')];
B = B(:);
3 Comments
Roger Stafford
on 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.)
Image Analyst
on 16 Feb 2015
Do a loop over rows, then call sort(). Alternate between 'ascend' and 'descend' options.
4 Comments
Image Analyst
on 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
See Also
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!