MATLAB: Need help with for loop and ploting.

for loop

This is the question
Problem 1: Use “for loop” write MATLAB program to calculate function f1, and plot function f1 = cos(x1), for x1 in the domain [0, pi]. (Choose increment of x1 to be 0.2)
Please include (a) Flow Chart (b) Matlab Script (c) A copy of the final Output (plot)
this is what I was able to come up with, can't seem to figure this out with a for loop.
for x1=0:.1:pi f1=cos(x1); f1=[x1,f1];
end hold on plot(x1,f1,'g')
What am I missing?

Best Answer

I would code it differently, but there are two changes you would need to make in your code:
f1 = []; % Initialise ‘f1’ As Empty
for x1=0:.1:pi
f=cos(x1); % Use a Different Variable Here
f1=[f1 f]; % Concatanate the New Value With Previous
end
Reproduce your ‘x1’ vector in your for loop statement to plot your function.