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

回答 (2 件)

madhan ravi
madhan ravi 2019 年 4 月 9 日

1 投票

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
Star Strider
Star Strider 2019 年 4 月 9 日

0 投票

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.

カテゴリ

ヘルプ センター および File Exchange2-D and 3-D Plots についてさらに検索

製品

リリース

R2019a

質問済み:

2019 年 4 月 9 日

コメント済み:

2019 年 4 月 9 日

Community Treasure Hunt

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

Start Hunting!

Translated by