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

1 次查看(过去 30 天)
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');

类别

Help CenterFile Exchange 中查找有关 Shifting and Sorting Matrices 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by