How its possible do define this function in Matlab?
1 view (last 30 days)
Show older comments
Hello everyone! Im new to Matlab and i have a little problem.
I have tried to define this function like this:
function F = func(t)
time = t>=0 && t<1; F(time) = t+1;
time = t>=1 && t<2; F(time) = 0;
time = t>=2 && t<3; F(time) = 2-t;
time = t>=3; F(time) = 0;
end
But, it gives me error(picture below):
Can you help me, please
0 Comments
Accepted Answer
Jan
on 6 Oct 2021
Edited: Jan
on 6 Oct 2021
Your funcion is almost correct. Just change && to & and consider the logical index time in the output.
The problem in your case was a symbolic input. The function requires a numerical input:
func(linspace(0, 4, 20))
function F = func(t)
time = t>=0 & t<1; F(time) = t(time) + 1;
time = t>=1 & t<2; F(time) = 0;
time = t>=2 & t<3; F(time) = 2 - t(time);
time = t>=3; F(time) = 0;
end
A slight simplification:
function F = func(t)
F = zeros(size(t)); % Pre-allocation
time = (t>=0 & t<1);
F(time) = t(time) + 1;
time = (t>=2 & t<3);
F(time) = 2 - t(time);
end
0 Comments
More Answers (1)
KSSV
on 6 Oct 2021
Edited: KSSV
on 6 Oct 2021
function g = func(t)
if t >=0 && t < 1
g = t+1 ;
elseif t >= 1 && t < 2
g = 0 ;
elseif t >= 2 && t < 3
g = 2-t ;
elseif t >= 3
g = 0 ;
end
Save the above and call it as:
g = func(0) ;
Your function should be:
function F = func(t)
time = t>=0 & t<1; F(time) = t(time)+1;
time = t>=1 & t<2; F(time) = 0;
time = t>=2 & t<3; F(time) = 2-t(time);
time = t>=3; F(time) = 0;
end
0 Comments
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!