# How to plot a graph with a for loop

33 views (last 30 days)
Yuvraj Bhagotra on 20 Jan 2021
Commented: Yuvraj Bhagotra on 20 Jan 2021
I have a question where I'm required to create a for loop and then use it to plot a graph. I have n = 0,1,2 ... 10 and need to plot cos(n*pi*x/2) for this. My current code looks like this as I'm trying to store the outputs of the for loop in an array
syms x n b a
nvalues = zeros(1, 10);
for n = 1:11
S = cos((n-1)*pi*x*(1/2));
nvalues(n) = S;
end
nvalues
Mathieu NOE on 20 Jan 2021
hello
figure, plot(1:max(n),nvalues)

Image Analyst on 20 Jan 2021
You need to define x with linspace() and then use hold on in the loop:
x = linspace(0, pi/4, 500);
for n = 0 : 10
S = cos(n*pi*x / 2);
%nvalues(n) = S;
plot(x, S, 'LineWidth', 2);
hold on;
end
grid on;
xlabel('x', 'FontSize', 16);
ylabel('S', 'FontSize', 16);
title('11 curves', 'FontSize', 16);
Yuvraj Bhagotra on 20 Jan 2021
Ah wow thats nice, thanks!

Bram Schroeders on 20 Jan 2021
Datapoints = 1000;
x = linspace(0,2*pi,Datapoints);
S = zeros(size(x));
hold all
for n = 1:11
S = cos((n-1)*pi*x*(1/2));
plot(x,S);
end
This should do the trick, you won't need the symbolic toolbox for this.
You can also save all the data by making a matrix out of S.
Yuvraj Bhagotra on 20 Jan 2021
Brilliant thanks!

VBBV on 20 Jan 2021
%if true
figure,
plot(1:10,nvalues)