Question about sorting an array column by column

조회 수: 4 (최근 30일)
helen orins
helen orins 2021년 9월 27일
댓글: helen orins 2021년 9월 27일
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
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()
helen orins
helen orins 2021년 9월 27일
Each column is sorted independently. So column 1, in ascending order. Done. Next, column 2, and so on. Hence the loop. So that's why I created the function. The rows are untouched.

댓글을 달려면 로그인하십시오.

답변 (2개)

the cyclist
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
helen orins
helen orins 2021년 9월 27일
I tried that, but this is the error I got: Unable to perform assignment because the size of the left side is 1073-by-1 and the size of the right side is 16095-by-1.
the cyclist
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 = 3×3
8 1 6 3 5 7 4 9 2
M = sort(M)
M = 3×3
3 1 2 4 5 6 8 9 7
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
Steven Lord 2021년 9월 27일
Specify the dim input argument to the sort function.
A = magic(5)
A = 5×5
17 24 1 8 15 23 5 7 14 16 4 6 13 20 22 10 12 19 21 3 11 18 25 2 9
B = sort(A, 1)
B = 5×5
4 5 1 2 3 10 6 7 8 9 11 12 13 14 15 17 18 19 20 16 23 24 25 21 22
% Compare with
C = sort(A, 2)
C = 5×5
1 8 15 17 24 5 7 14 16 23 4 6 13 20 22 3 10 12 19 21 2 9 11 18 25
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
D = 5×5
23 5 7 14 16 4 6 13 20 22 10 12 19 21 3 11 18 25 2 9 17 24 1 8 15

카테고리

Help CenterFile Exchange에서 Data Distribution Plots에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by