How do I plot my function that I made? It's piecewise.
Show older comments
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
1 Comment
Stephen23
on 9 Apr 2019
Forget about IF, you should vectorize your code using logical indexing:
Answers (2)
madhan ravi
on 9 Apr 2019
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
on 9 Apr 2019
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.
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!