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:
What's the fastest way (no for loop) of doing matrix indexing?

Subject: What's the fastest way (no for loop) of doing matrix indexing?

From: Luna Moon

Date: 30 Nov, 2010 15:38:50

Message: 1 of 3

What's the fastest way (no for loop) of doing matrix indexing?

Hi all,

I have two matrics A and B, both are M x N.

And I have a M x 1 vector v, containing 0s and 1s.

Would like to compose a new mixed matrix C, as follows:

for the i-th row, if v(i)==0, we would like to have C(i, :)=A(i, :);

if v(i)==1, we would like to have C(i, :)=B(i, :).



We've tried:

AB(1, :, :)=A;
AB(2, :, :)=B;

C=AB(v+1, :, :);

But it doesn't work...

How to do this fast without using "for loop"?

Thank you!

Subject: What's the fastest way (no for loop) of doing matrix indexing?

From: Matt J

Date: 30 Nov, 2010 15:45:20

Message: 2 of 3

Luna Moon <lunamoonmoon@gmail.com> wrote in message <6d26b39a-4bb0-44b7-ad8c-f76918c9d47e@32g2000yqz.googlegroups.com>...
> What's the fastest way (no for loop) of doing matrix indexing?
>
> Hi all,
>
> I have two matrics A and B, both are M x N.
>
> And I have a M x 1 vector v, containing 0s and 1s.
>
> Would like to compose a new mixed matrix C, as follows:
>
> for the i-th row, if v(i)==0, we would like to have C(i, :)=A(i, :);
>
> if v(i)==1, we would like to have C(i, :)=B(i, :).

v=logical(v);
C=A;
C(v,:)=B(v,:);

Subject: What's the fastest way (no for loop) of doing matrix indexing?

From: Walter Roberson

Date: 30 Nov, 2010 16:50:12

Message: 3 of 3

On 30/11/10 9:38 AM, Luna Moon wrote:
> What's the fastest way (no for loop) of doing matrix indexing?

> I have two matrics A and B, both are M x N.
>
> And I have a M x 1 vector v, containing 0s and 1s.
>
> Would like to compose a new mixed matrix C, as follows:
>
> for the i-th row, if v(i)==0, we would like to have C(i, :)=A(i, :);
>
> if v(i)==1, we would like to have C(i, :)=B(i, :).

I do not promise that the below is the fastest, but it is loop-free.

v = logical(v);
C=zeros(size(A));
C(v,:) = B(v,:);
C(~v,:) = A(~v,:);

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