hei,
i have a 3d matrix, where each layer into the 3rd dimension is a new measurement. the value in one cell however gives me the distance. now i would like to sort these layer by this cell (distance).
this is possible within a 2d matrix with the function 'sortrows'.
thanks for help ;-) markus

 採用された回答

Laura Proctor
Laura Proctor 2011 年 11 月 14 日

1 投票

From what I understand, you just want to sort by an element on each page in the 3D array - this is how you can do it:
A = randi(10,[4,4,4])
[~,idx] = sort(A,3); % sort by the page
iv = zeros(1,size(A,3)); % set up the indexing vector
iv(:) = idx(1,1,:); % find the ordering of the (1,1)
% element by which to sort A
B = A(:,:,iv) % sort A according to the (1,1)
% element of each page

2 件のコメント

Markus
Markus 2011 年 11 月 14 日
hei laura,
thanks for your answer. if i read your code right, you sorted the pages by cell (1,1,:) which is the same position in A and idx.
;-) markus
Laura Proctor
Laura Proctor 2011 年 11 月 14 日
You got it!

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

その他の回答 (1 件)

Sven
Sven 2011 年 11 月 14 日

1 投票

Hi Markus,
If you have a 3D MATRIX of numbers, and the distance you want to sort by is stored, say, in the (1,1) location of each slice in the third dimension, try:
A = rand(5,5,10);
[~,sortOrder] = sort(A(1,1,:),3);
A_sorted = A(:,:,sortOrder);
If you have a 3D CELL of numbers, read below:
Unfortunately when passing a cell to sort(), it expects that cell to be a cell of strings. The only way to sort numeric data in a cell is to convert it to a matrix, as below:
Let's first make your data into a cell (I'm only including "distance"... I presume since your data is in a cell to start with then there's a good reason you didn't store it as a vector of distances):
distanceCell = num2cell(rand(1,1,20))
We then just make a vector from only the numeric values in the cell
distancesVector = cat(1,distanceCell{1,1,:});
Then we sort that vector and reorder the cell accordingly.
[~, sortOrder] = sort(distancesVector);
sortedCell = distanceCell(:,:,sortOrder);

3 件のコメント

Markus
Markus 2011 年 11 月 14 日
it is the first case. thats what i needed!! thanks..
Markus
Markus 2011 年 11 月 14 日
aehm, i also accept your answer .. :) but i read laura first.
Sven
Sven 2011 年 11 月 14 日
Aha, no problems Markus

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

カテゴリ

ヘルプ センター および File 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