# Plotting graph using for loop in MATLAB

### Why this happens…

With `plot(x(i),y)` you are plotting 100 single points (one in each iteration) and they are not shown by default. Therefore the plot looks empty.

### Solution 1: Vectorized calculation and direct plot

I assume you meant to draw a continuous line. In that case no for-loop is needed because you can calculate and plot vectors directly in MATLAB. So the following code does probably what you want:

``````x = linspace(0,2*pi,100);
y = sin(x);
plot(x,y);
``````

Note that `y` is a vector as well as `x` and that `y(n)` equals to `sin(x(n))` for all `n`. If you want to plot the points itself, use LineSpec-syntax when calling `plot` like this1:

``````plot(x,y,'*');
``````

1) Other types of points are possible as well, see the above linked documentation.

### Solution 2: Calculate values within for-loop and plot afterwards

If you want to calculate the values within a for-loop and plot it afterwards: Pre-allocate the needed variable (in this case `y`), calculate the values within the for-loop and finally plot it with one single command after the calculation.

``````x = linspace(0,2*pi,100);

y = zeros(size(x));
for i = 1:numel(x)
y(i) = sin(x(i));
end

plot(x,y);
``````

### Solution 3: Dynamically update plot while calculating

In case you insist on plotting within each iteration, the previous code from Solution 2 can be expanded as follows: Create a figure, add an ’empty’ plot to it and store its handle. Within the for-loop calculate the values and add them to the `y`-vector as shown above. As a last step you can update the plot by changing its `XData` and `YData` properties and calling `drawnow`. Note that calling `plot` every time within the for-loop is unnecessarily expensive and I don’t recommend it.

``````% create figure and plot
figure;
ph = plot(0,0);
ax = gca;
set(ax,'XLim',[0,2*pi]);
set(ax,'YLim',[-1,1]);

% calculate and update plot
x = linspace(0,2*pi,100);
y = zeros(size(x));
for i = 1:numel(x)
y(i) = sin(x(i));
set(ph,'XData',x(1:i));
set(ph,'YData',y(1:i));
drawnow;
end
``````