How can I sort an input matrix according to some value, where the matrix rows are variable in size ?

1 view (last 30 days)
Hello, I have a problematic sorting operation. In one matrix(say A) I have some location ID's, and in another array(say dist) I store the distance values at the positions corresponding to zone ID's. What I want to do is sort each row of A according to their distance values and retrieve the sorted zone ID's. The problem is Matlab reads A from an Excel file, where each row is of unknown length. Therefore it fills the empty elements with NaN (which is OK for the remaining of the code). However, because of NaN I cannot sort A according to Distance values ( due to dist(NaN) entries). Any suggestions or any other possible methods for this sorting operation? Thanks.

Answers (1)

Image Analyst
Image Analyst on 19 Dec 2015
Not sure if you're sorting in ascending or descending order but here's a neat trick: Use isnan() to set all the nan locations to either inf or -inf, depending on the sort directtion. After that they should sort fine.
data(isnan(data)) = inf;
sortedData = sort(data, 'ascend');
or
data(isnan(data)) = -inf;
sortedData = sort(data, 'descend');
  1 Comment
osygl
osygl on 19 Dec 2015
OK, but again I cannot use inf as an indice, since I try to make to sort according to distance values which is stored in another array.

Sign in to comment.

Categories

Find more on Shifting and Sorting Matrices 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!