MATLAB: Sort matrix by ratios of the adjacent column

matrix sortingratios

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];

Best 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.