Sort matrix by ratios of the adjacent column

imagine I have a matrix [1, 5; 1, 2; 1, 3]; and I want to rearrange the matrix depending on its ratio with between the two columns so the output is [1, 5; 1, 3; 1, 2];

3 Comments

Um, bad example. Your input AND output are identical: [1, 5; 1, 2; 1, 3]
Did you make a mistake?
sorry about that just updated it
OK, I also updated my answer below.

Sign in to comment.

 Accepted Answer

Try this:
m = [1, 5; 1, 2; 1, 3]
ratios = m(:, 1) ./ m(:, 2) % Compute ratio of column 1 to column 2
output = sortrows([m, ratios], 3, 'ascend') % or 'descend'
output = output(:, 1:2) % Get just the first two columns, not the ratio column.

More Answers (0)

Categories

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!