thDvrs
thDvrs

Reputation: 33

How to sort the rows of a multidimensional matrix in Matlab without changing the order of the elements in the first column?

I have a 3D matrix A(i, j, k). The problem is the following:

I have a number of rooms. I use the first dimension (the i's) to denote the room IDs. Each room has a number of chairs in it. I use the 2nd dimension (the j's) to denote the chairs' IDs. Each chair has coordinates x,y,z. I use the 3rd dimension (the k's) to denote the coordinates.

For example, A(4,3,1) denotes the 4th room, 3rd chair, x-coordinate; A(4,3,2) denotes the same room and chair but the y-coordinate; and A(4,3,3) the z-coordinate.

I need to sort the chairs in each room independently of the other rooms, according to one of the dimensions.

Let's say I want to sort the chairs of the first room only, that is A(1 , : , :), according to their x-coordinate, that is A(1 , : , 1).

Could anyone help me on how to do that in Matlab 2016b?

Thanks a lot!

Upvotes: 2

Views: 70

Answers (1)

Luis Mendo
Luis Mendo

Reputation: 112679

I think this does what you want:

A = randi(99,3,3,3); % example data
room = 1; % desired room
coord = 1; % desired coordinate
[~, ind] = sort(A(room,:,coord)); % get indices of the sorting
B = A; % result. Initiallize
B(room,:,:) = B(room,ind,:); % apply sorting to chairs in that room

Upvotes: 5

Related Questions