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

1 回表示 (過去 30 日間)
osygl
osygl 2015 年 12 月 19 日
コメント済み: osygl 2015 年 12 月 19 日
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.

回答 (1 件)

Image Analyst
Image Analyst 2015 年 12 月 19 日
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 件のコメント
osygl
osygl 2015 年 12 月 19 日
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.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeShifting and Sorting Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by