if statement for piecewise function

4 views (last 30 days)
Rana Önem
Rana Önem on 23 Nov 2021
Answered: Walter Roberson on 23 Nov 2021
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?

Answers (1)

Walter Roberson
Walter Roberson on 23 Nov 2021
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!