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:
how to conditional vector operation

Subject: how to conditional vector operation

From: Bruce Heu

Date: 28 Apr, 2011 02:58:04

Message: 1 of 2

A = [1 2 3 4 5;4 3 2 5 2;6 4 2 1 9]

B=1 X 5 vector

Calculate one bye one
for i=1:5
if A(2,i)>3,
B1(i,1)=A(1,i);
else
B1(i,1)=A(3,i);
end
end

I get B1 =

     1
     4
     2
     4
     9

Is there anyway to do in a vector way like following instead of doing one by one?
if A(2,:)>3,
B2(:,1)=A(1,:);
else
B2(:,1)=A(3,:);
end

I got
B2=
     6
     4
     2
     1
     9

why they are different? Please help. Thanks.

Subject: how to conditional vector operation

From: Roger Stafford

Date: 28 Apr, 2011 05:21:04

Message: 2 of 2

"Bruce Heu" wrote in message <ipal3s$813$1@fred.mathworks.com>...
> ......
> Is there anyway to do in a vector way like following instead of doing one by one?
> ......
> why they are different? Please help. Thanks.
- - - - - - - - -
   You need to get a vector of true's and false's as with 't' in the following and do arithmetic with it:

 t = A(2,:)>3;
 B1 = t.*A(1,:)+(~t).*A(3,:);

  Your if-else-end failed because an "if" condition is a single entity, either true or false, not a vector series of true's and false's. You would have gotten a true if all(A(2,:)>3) were true, otherwise it is false.

Roger Stafford

Tags for 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