if statement for piecewise function
6 次查看(过去 30 天)
显示 更早的评论
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?
0 个评论
回答(1 个)
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.
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Numeric Types 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!