How its possible do define this function in Matlab?

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

 Réponse acceptée

Jan
Jan le 6 Oct 2021
Modifié(e) : Jan le 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))
ans = 1×20
1.0000 1.2105 1.4211 1.6316 1.8421 0 0 0 0 0 -0.1053 -0.3158 -0.5263 -0.7368 -0.9474 0 0 0 0 0
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

Plus de réponses (1)

KSSV
KSSV le 6 Oct 2021
Modifié(e) : KSSV le 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

Catégories

En savoir plus sur MATLAB dans Centre d'aide et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by