MATLAB: Error in plotting clipped sinewave

for loopif statementMATLABplottingSymbolic Math Toolboxtime defined functions

K=1;
UpD=input('Enter value of alpha in radian =');
DwD=input('Enter value of gamma in radian =');
for t=0:0.000001:2*pi
if t<UpD
y=0;
elseif pi<t<DwD
y=0;
else
y=K*sin(t)
end
end
plot(t,y)
grid
title('Distorted signal wave')
xlabel('Phase angle in degree')
ylabel('y(wo)')
I am trying to plot clipped sinewave and I expect my output to be like in the figure below but instead I am getting blank

Best Answer

Your problem is that y is not a vector. In the case of your posted code, y will be the value that it is set to on the last pass through your for loop (sin(2*pi) or a nearly zero number, due to floating point precision). So, the plot will be a about 6 million points at nearly zero which you won't be able to see (plot will expand your scalar y to match the dimensions of t -- not that I agree with that feature, but it is true).
So here are a couple of things you should consider:
  • If you wish to use a loop (which is OK for learning), add an index to the calculation of y. To do this, you should define your time vector before the loop and then loop over the elements of t and wherever you assign y, assign a new element of the y array based on the currently indexed value of the t array, using the loop index. Note that, for efficiency, you should pre-allocate your y array before the loop (make a space in memory for it so that Matlab doesn't have to keep finding a new space in memory for it as it grows during the loop). For example:
t = 0:0.01:2*pi;
y = zeros(size(t));
for idx = 1:numel(t)
if t(idx) < UpD
y(idx) = 0;
...
end
  • Do you really believe that your monitor is going to be able to display over 6 million points along your x axis? If not, reduce the step size of your t vector.
Note that there are more efficient ways to do this, without a loop, using logical indexing, for example. Search the Matlab help for that when you want to learn more.