Best way to sort a 3-d matrix by one column?

20 ビュー (過去 30 日間)
Emily Hokett
Emily Hokett 2018 年 10 月 11 日
回答済み: Guillaume 2018 年 10 月 15 日
Hi, I'd like to sort a 3 d matrix by the values in one column. I have a 204 x 33 x 9 matrix, and I'd like to sort the rows by the 33rd column of the second dimension. Thanks, Emily
  2 件のコメント
Guillaume
Guillaume 2018 年 10 月 11 日
編集済み: Guillaume 2018 年 10 月 11 日
Should each page be sorted separately or should it just be considered flattened into 2d? A short example of input/desired output would be useful.
Emily Hokett
Emily Hokett 2018 年 10 月 15 日
Each page would sorted separately by the 33rd column so that it's still a 3-d matrix, just the rows would be sorted by the values in the 33rd column.

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

回答 (2 件)

gonzalo Mier
gonzalo Mier 2018 年 10 月 11 日
I am not sure if this is what you want:
matrix(:,33,2) = sort(matrix(:,33,2));
  3 件のコメント
gonzalo Mier
gonzalo Mier 2018 年 10 月 11 日
Can you put an example of what you want?
Emily Hokett
Emily Hokett 2018 年 10 月 15 日
Okay, I just want to now if it's possible to somehow use sortrows for a 3-d matrix. If I have 204 rows, 33 columns, and 9 pages, could I sort the 204 rows by the values in the 33rd column and do this for all 9 pages?

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


Guillaume
Guillaume 2018 年 10 月 15 日
You can't use sortrows on a 3D matrix. You have two options:
  • Use a loop and use sortrows on the pages:
for page = 1:size(yourmatrix, 3)
yourmatrix(:, :, page) = sortrows(yourmatrix(:, :, page), 33);
end
  • Use sort and some sub2ind magic to sort everything at once. I'm not sure it'll be faster than the loop:
[~, roworder] = sort(yourmatrix(:, 33, :));
sortedmatrix = yourmatrix(sub2ind(size(yourmatrix), ...
repmat(roworder, 1, size(yourmatrix, 2), 1), ...
repmat(1:size(yourmatrix, 2), size(yourmatrix, 1), 1, size(yourmatrix, 3)), ...
repmat(permute(1:size(yourmatrix, 3), [1 3 2]), size(yourmatrix, 1), size(yourmatrix, 2), 1)));

カテゴリ

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