MATLAB: Is the line not showing up on the plot

forfor loopgraphgraphicgraphicslinelinesplot

I'm trying to plot a line by using a for loop to fill one array but it's not working. Here's an example of what doesn't work:
close all
figure
hold on
%this doesn't work
y= zeros(1, 10);
i=1;
for x= 0:.1:10
y(i)= sin(x);
i=i+1;
end
plot(x, y)
%this works though
x= 0:.1:10;
y= cos(x);
plot(x, y)
hold off
What am I doing wrong with the for loop?

Best Answer

The loop does not work because x is not a vector after the loop. You have used x as the index variable, which is a scalar. Change your loop to this:
x = 0:.1:10;
y = zeros(size(x));
for i=1:numel(x)
y(i)= sin(x(i));
end
Now x is still a vector after the loop.
Related Question