Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

Thread Subject:
Accessing row elements in multi-dimensional matrix

Subject: Accessing row elements in multi-dimensional matrix

From: Alexandra

Date: 17 May, 2011 13:56:03

Message: 1 of 2

Hello,

I have 2 matrices. Matrix A is of size 1 x 3 x 2 and matrix B is of size 5 x 3 x 2.

I want to create a third matrix, C, of size 1 x 3 x 2 which contains elements of B at the rows defined in matrix A.

Here's an example:

A(:,:,1) = [1 3 2]
A(:,:,2) = [5 3 4]
B(:,:,1) = [10 11 12;13 14 15;16 17 18;19 20 21;22 23 24]
B(:,:,2) = [25 26 27;28 29 30;31 32 33;34 35 36;37 38 39]

So, I want to get:
C(:,:,1) = [10 17 15]
C(:,:,2) = [37 32 36]

Is there a way of doing this without loops?

Thanks for the help!

Subject: Accessing row elements in multi-dimensional matrix

From: Florin Neacsu

Date: 17 May, 2011 17:40:04

Message: 2 of 2

"Alexandra" wrote in message <iqtupj$6g8$1@newscl01ah.mathworks.com>...
> Hello,
>
> I have 2 matrices. Matrix A is of size 1 x 3 x 2 and matrix B is of size 5 x 3 x 2.
>
> I want to create a third matrix, C, of size 1 x 3 x 2 which contains elements of B at the rows defined in matrix A.
>
> Here's an example:
>
> A(:,:,1) = [1 3 2]
> A(:,:,2) = [5 3 4]
> B(:,:,1) = [10 11 12;13 14 15;16 17 18;19 20 21;22 23 24]
> B(:,:,2) = [25 26 27;28 29 30;31 32 33;34 35 36;37 38 39]
>
> So, I want to get:
> C(:,:,1) = [10 17 15]
> C(:,:,2) = [37 32 36]
>
> Is there a way of doing this without loops?
>
> Thanks for the help!

Hi,

Try this

A(:,:,1) = [1 3 2];
A(:,:,2) = [5 3 4];
B(:,:,1) = [10 11 12;13 14 15;16 17 18;19 20 21;22 23 24];
B(:,:,2) = [25 26 27;28 29 30;31 32 33;34 35 36;37 38 39];


[a,b,c]=size(A);
[m,n,p]=size(B);

%check b=c and c=p ??

temp=0:m:(c+b)*m;
temp=reshape(temp,b,c);
A=squeeze(A)';
A=A+temp';
B(A)

Regards,
Florin

Tags for this Thread

No tags are associated with this thread.

What are tags?

A tag is like a keyword or category label associated with each thread. Tags make it easier for you to find threads of interest.

Anyone can tag a thread. Tags are public and visible to everyone.

Contact us