Reputation: 2158
I am newbie in matlab and writing a function code with the aim of helping to plot of half-wave rectified sine function. But it doesn't give me the result what I expect.
function x = rectifiedSineWave(t )
if sin(t) < 0
x = 0;
else
x = sin(t);
end
Upvotes: 1
Views: 549
Reputation: 5024
If t
has just one element, your original code looks fine.
If t
is a vector, you probably want
function x = rectifiedSineWave(t)
x = sin(t);
x(x<0)=0;
or, even simpler (thanks to Serg)
function x = rectifiedSineWave(t)
x = max(0, sin(t));
This way elements where sin(t)
is negative are set to zero.
Your problem was that if sin(t)<0
triggers as soon as any element of the vector t
is negative, and will set x
to zero.
Upvotes: 4