On 101116 01:34 PM, Sean de wrote:
> "C Meek" <meeky2000@hotmail.com> wrote in message
> <ibulqg$d49$1@fred.mathworks.com>...
>> I'd like to write a Matlab command that does the following:
>>
>> f(x)={ 2, x>=3
>> { 3, x<3
>>
>> Is the best way to do this using if..else statements or is there a
>> better way?
>>
>> Thanks for any help
>
> Better than if statements because it's vectorized (you can pass in a
> matrix or vector instead of a scalar)
> %%%
> x(x>=3) = 2;
> x(x<3) =3;
That isn't going to work. Suppose you start with x(7) = 4. Then the first
subclause x>=3 is going to be true at position 7, so you would set that
position to 2. Then when you got to the second statement, x < 3 would now be
true for that 7th position because the location get set to 2 a moment ago, so
the location would get set to 3. The end result would be x(7) being 3 whereas
clearly your description would want it to end up being 2.
You could use
2 + (x<3)
as the expression. That does have a problem, but only with respect to a result
you did not define. If one of the locations is NaN, then x<3 will be false,
and you would generate 2 for that location, implying that NaN >= 3 which is
also false. NaN does not match either of your conditions, so f(NaN) is
undefined for you rather than having a particular value. Fixing this gets obscure.
