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

 Respuesta aceptada

Walter Roberson
Walter Roberson el 18 de Abr. de 2012
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 comentarios

Xiaochen
Xiaochen el 23 de Abr. de 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
Walter Roberson
Walter Roberson el 23 de Abr. de 2012
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.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Elementary Math en Centro de ayuda y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by