if statement for piecewise function

조회 수: 2(최근 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;
elseif t>10,t<20;
and i got an error like this " Not enough input arguments." so what am i doing wrong? can you help me?


VBBV 2021년 11월 23일
syms t
beta = 10;
p = piecewise(0<t<10,0.3*beta,10<t<20,-0.3*beta,0)
p = 
fplot(p,[0 20],'linewidth',2)
axis([0 20 -5 5])

Walter Roberson
Walter Roberson 2021년 11월 23일
p = zeros(size(t));
for K = 1 : numel(t)
if t(K)>0 && t(K)<10
elseif t(K)>10 && t(K)<20
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.

Community Treasure Hunt

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

Start Hunting!

Translated by