How do I plot my function that I made? It's piecewise.

I need to plot this graph on the interval (-2,20), I'm also supposed to use a for loop to plot but I don't know how.
function y = y(t)
if (t < 0)
y = -9;
elseif ((0 <= t)&& (t < 10))
y = -9*cos(3*t);
elseif (t >= 10)
y = -9*cos(3*t)*(exp(-0.1*(t-10)));
end
end
Thanks a lot

Réponses (2)

Try this:
% Logical indexing is the way I would do it but since you requested
t=-2:.001:20;
plot(t,Y(t))
% ^^^^---function call
function y = Y(t) %function definition
y = zeros(size(t)); % pre-allocate
for k=1:numel(t)
if (t(k) < 0)
y(k) = -9;
elseif ((t(k) >= 0)) && (t(k) < 10)
y(k) = -9*cos(3*t(k));
elseif (t(k) >= 10)
y(k) = -9*cos(3*t(k))*(exp(-0.1*(t(k)-10)));
end
end
end
I generally use Anonymous Functions (link) for these problems:
y = @(t) -9*(t < 0) + (-9*cos(3*t)).*((0 <= t) & (t < 10)) + (-9*cos(3*t).*(exp(-0.1*(t-10)))).*(t >= 10);
t = linspace(-5, 75, 500);
figure
plot(t, y(t))
grid
Note that ‘short circuit’ (duplicate) operators, such as ‘&&’ and ‘||’ only work for logical scalars, not logical vectors.

Catégories

En savoir plus sur 2-D and 3-D Plots dans Centre d'aide et File Exchange

Produits

Version

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by