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 ExchangeElementary Math についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by