Question about sorting an array column by column
6 次查看(过去 30 天)
显示 更早的评论
I need to sort each column of a 1073x15 array for a heatmap in MATLAB.
[~,sortdices] = sort(choose_data(:,1),'ascend');
%choose_data = choose_data(:,sortdices);
for i=1:15
choose_data(:,i) = choose_data(sortdices,i)
end
this is my code. choose_data is the 1073x15 array. My output ends up being the first column sorted in ascending order, but the rest not. How do I fix it, such that all columns are sorted in ascending order? (Thank you for any help!)
2 个评论
Walter Roberson
2021-9-27
Is each column to be sorted independently, or should the columns be sorted "within" each previous column? That is, if two rows have the same value for column 1, then look at column 2 to determine the order; if those are equal, look at column 3, and so on ? If so then sortrows()
回答(2 个)
the cyclist
2021-9-27
编辑:the cyclist
2021-9-27
choose_data = sort(choose_data)
will sort every column independently. Ascending sorting is the default, so you don't need to specify that. (But it also doesn't hurt, and might make the code clearer.)
2 个评论
the cyclist
2021-9-27
编辑:the cyclist
2021-9-27
Strange. Here is an example that illustrates that the syntax works:
M = magic(3)
M = sort(M)
Note that you do not need to do anything in a for loop. That one line of code will sort all columns of the array. You also don't need to do any indexing into the array.
Steven Lord
2021-9-27
Specify the dim input argument to the sort function.
A = magic(5)
B = sort(A, 1)
% Compare with
C = sort(A, 2)
If you want to sort one of the columns and have the rest of the rows rearrange correspondingly see the sortrows function.
D = sortrows(A, 2) % sort by column 2
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Data Distribution Plots 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!