if statement for piecewise function

6 ビュー (過去 30 日間)
Rana Önem
Rana Önem 2021 年 11 月 23 日
回答済み: Walter Roberson 2021 年 11 月 23 日
I have a piecewise function like :
p(t) = ( 0.30*beta 0<t<10 s
-0.30*beta 10<t<20 s
0 t<20 s )
i write this on matlab like this:
if t>0,t<10;
p(t)=0.30*beta;
elseif t>10,t<20;
p(t)=-0.30*beta;
else
p(t)=0;
end
and i got an error like this " Not enough input arguments." so what am i doing wrong? can you help me?

回答 (1 件)

Walter Roberson
Walter Roberson 2021 年 11 月 23 日
p = zeros(size(t));
for K = 1 : numel(t)
if t(K)>0 && t(K)<10
p(K)=0.30*beta;
elseif t(K)>10 && t(K)<20
p(K)=-0.30*beta;
else
p(K)=0;
end
end
Notice that if you are going to use if statements and t is a vector, then you need to loop over all of the entries in the vector.
However, in many cases, it is better to use logical indexing instead of looping.
p = zeros(size(t));
mask = t > 0 & t < 10;
p(mask) = 0.30*beta;
mask = t > 10 & t < 20;
p(mask) = -0.30*beta;
No need for an else because all elements were initialized to 0 anyhow.
Caution: when t = 10 exactly your code falls through to the else and assigns 0 there.
Caution: your code does not implement the same as the function definition. The function definition does not define any value for complex-valued t or for t >= 20, but your code would assign 0 to those locations. When a function definition does not define a result for a case, the code should either error or generate NaN if that situation is encountered.

カテゴリ

Help Center および File ExchangeNumeric Types についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by