Plotting a piecewise function in MATLAB

I've been trying to plot a piecewise function: y(t)=a*sin(2*pi *f *t) for 0 < t asked Apr 15, 2020 at 16:25 11 2 2 bronze badges

Hi, and welcome to stack overflow! Your question is not very clear - what do you want to achieve? What have you tried? Why did it not work? stackoverflow.com/help/how-to-ask might help you to improve it!

Commented Apr 15, 2020 at 17:17

2 Answers 2

in matlab, usually plots are done by computing the x/y values in a discretized grid.

f=2; a=1; t=0:0.01:3; y=zeros(size(t)); y(t 

another way to create such a piece-wise function is to create a dedicate function or anonymous function to compute this in real time. For example

y=@(t,f,a) (t=0).*sin(2*pi*f*t)*a; plot(t,y(t,f,a)) 
answered Apr 15, 2020 at 16:30 1,532 10 10 silver badges 21 21 bronze badges

I'm clearly not used to asking questions on this site;;; Could you plz take a look at what I'm doing wrong? I posted my new question below.

Commented Apr 15, 2020 at 16:55

I was trying sth like this:

function [rate] = y(a,f,t)
for t = (0:3)
if t rate = a * sin(2 * pi * f * t);
else
rate = 0;
end
end
end

and then call: plot (t, y(a,f,t)) to plot the graph. Could you correct me if I'm wrong?

answered Apr 15, 2020 at 16:53 11 2 2 bronze badges

several issues: 1) your function y defines t inside, so, you do not have to pass on t to y because it already knows it. 2) but the issue then is your t has a fixed range. to make it flexible, you should write your y to convert a single value of t using it as an input. Basically, remove the for loop. 3) your t=0:3 vector is too sparse - 0:3 means [0 1 2 3] with 1 as spacing, it is not enough to show the curve.