Piecewise Function with a Vector

4 views (last 30 days)
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

Accepted Answer

Walter Roberson
Walter Roberson on 18 Apr 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 Comments
Xiaochen
Xiaochen on 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
Walter Roberson
Walter Roberson on 23 Apr 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.

Sign in to comment.

More Answers (0)

Categories

Find more on MATLAB in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!