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

 채택된 답변

Walter Roberson
Walter Roberson 2012년 4월 18일

1 개 추천

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

Xiaochen
Xiaochen 2012년 4월 23일
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 2012년 4월 23일
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.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Elementary Math에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by