Search All of the Math Forum:

Views expressed in these public forums are not endorsed by NCTM or The Math Forum.

Notice: We are no longer accepting new posts, but the forums will continue to be readable.

Topic: Vector comparison using if
Replies: 4   Last Post: Nov 20, 2012 4:04 AM

 Messages: [ Previous | Next ]
 Jos Posts: 1,268 Registered: 10/24/08
Re: Vector comparison using if
Posted: Nov 20, 2012 4:04 AM

"Rajasekhara Madhusudan Narayana Bhatla" <rmnaraya@asu.edu> wrote in message <k8eno8\$k9d\$1@newscl01ah.mathworks.com>...
> Hi,
> I'm sought of new using matlab. I've a situation where I've to assign a variable 2 different values based on how the values in vector
>
> it is something like.
> fs=1000;
> x=1:4/fs:5;
> if x<2
> Y=x.^2
> else
> Y=4;
> end.
>
> i.e, my Y will also be a vector whose value depends on where I x is. if x is <2 then y is x^2 if not it is a constant.
>
> I'm not sure how to do this.
> i tried it with if any(x)<2 but I then i realized that it is not correct. since I want for all values of x<2 Y=x^2 and all values of x >2 x = 4.
>
>
> Thanks,
> Sekhar.

Learn about logical indexing, one of the great strengths of matlab. Here is an example:

x = 1:10
tf = x < 5 % a logical vector
y = zeros(size(x)) % pre-allocation
y(tf) = 1
y(~tf) = 10

~ Jos

Date Subject Author