Piecewise Function with a Vector

I am writing a matlab about my work.
There is a piecewise function in my code.
somelike:
sqrt(2*(1-P/3)) when P<0;
sqrt(4-2*(1-P/2)) when P>0
P is a vertor, P = 1.4-2/5*f + something;
f is 0:0.001:20
there is my question
I don't quite get how to do a piecewise function. Because nomarlly piecewise function look likes:
f(x)=1 when x>0
f(x)=2 when x<0
x is not a vector.
In my work, the P is a vector. I can not do 1.4-2/5*f + something > 0 or < 0
Therefore please help me and give me the idea of how to do it
Kind Regards

 Risposta accettata

function r = f(P)
r = NaN(size(P));
r(P<0) = sqrt(2*(1-P(P<0)/3));
r(P>0) = sqrt(4-2*(1-P(P>0)/2));
end
Notice this will give you NaN at the locations in which P is exactly 0, as you did not define the result for that case.

2 Commenti

Xiaochen
Xiaochen il 23 Apr 2012
but my p is still a vector which P = 1.4-f.*(something/something) + something.
Could I still use P < 0 or P >= 0 in the function?
Thanks a lot
Yes, the above code is vectorized, suitable for P being a vector.
If you change the > to >= as in your comment, then you can also change the NaN(size(P)) to zeros(size(P)) which will be more efficient.

Accedi per commentare.

Più risposte (0)

Categorie

Scopri di più su Elementary Math in Centro assistenza e File Exchange

Tag

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by