Sort columns in a matrix with respect to the means of each column
17 views (last 30 days)
Show older comments
Hello everybody,
I would like to sort the columns of a matrix with respect to the means of each column.
For instance, let's say I have 3 columns with 4 rows/values each:
1 6 2
1 2 3
2 7 5
2 8 4
and I would like to arrange the columns with respect to the means of the columns (i.e., 1.5 and 5.75 and 3.5, respectivly)
e.g. in an ascending order, that should result to the following new matrix:
1 2 6
1 3 2
2 5 7
2 4 8
Any recommendations on how to achieve this? Found various options for sorting, but so far didn't succeed in re-ordering according the the means.
Thanks a lot!
Stefan
0 Comments
Answers (2)
Scott MacKenzie
on 30 Jun 2021
Here's one way to do this:
M = [1 6 2;
1 2 3;
2 7 5;
2 8 4]
[~, idx] = sort(mean(M));
M(:,idx) = M
Output:
M =
1 6 2
1 2 3
2 7 5
2 8 4
M =
1 2 6
1 3 2
2 5 7
2 4 8
4 Comments
Ernst Jan Hölscher
on 24 Apr 2022
Edited: Ernst Jan Hölscher
on 24 Apr 2022
Thanks Scott. This has been very helpful to me. I have however failed to implemnt this without that intermediate step. Wondering if there's a way to access that second column of sort() results within that last statement.
Scott MacKenzie
on 24 Apr 2022
@Ernst Jan Hölscher, if you just want to access the 2nd column of the sort results, then use
M(:,idx(2))
after the 2nd statment in my solution, or
M(:,2)
after the 3rd statement.
Image Analyst
on 24 Apr 2022
Scott's code has an error. It should be
M = M(:, idx);
not
M(:, idx) = M;
Here's a full demo:
m = randi(9, 4, 7)
meansOfColumns = mean(m, 1)
% Sort by the means
[sortedMeans, sortOrder] = sort(meansOfColumns)
m = m(:, sortOrder) % Correct.
% m(:, sortOrder) = m % Not correct
% Verify by checking means again
meansOfColumns = mean(m, 1)
You'll see the columns are sorted in order of increasing column means. If you want to see Scott's way, comment out the "Correct" line and uncomment the "Not correct" line and you'll see the columns are not in order of increasing mean values.
1 Comment
Scott MacKenzie
on 24 Apr 2022
@Image Analyst, ah, yes, right you are. The error doesn't appear in the 3-column example, but it's obvious enough with a larger data set. Thanks for the correction. And it only took 10 months! :) I guess we can thank @Ernst Jan Hölscher for bringing this question back to the fore. Perhaps @Stefan Schulreich will now accept the correct answer.
See Also
Categories
Find more on Matrix Indexing 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!