How to plot a function within a for loop?
51 views (last 30 days)
Show older comments
I am trying to graph the resulting output of my function in a for loop, but all that comes up is a blank graph.
Any help is appreciated
Accepted Answer
Voss
on 29 Jul 2022
You're plotting one point at a time there, which won't appear unless you use a data marker. And even then you'll only see the last one without turning hold on
% F = input('Value for F: ')
F = 3;
figure()
hold on % hold on to see all the points
for i = .05:.05:.95
term = F*((1/(1-i)^1)^.8+11*(1/i)^.4);
fprintf('Cost is %4.1f for Xa %1.2f\n', term,i)
plot(term,'o') % data marker
end
There you go - there's a plot of all the term values.
I imagine it would be better to plot the term values as a function of i, which might look like this:
figure()
hold on
for i = .05:.05:.95
term = F*((1/(1-i)^1)^.8+11*(1/i)^.4);
fprintf('Cost is %4.1f for Xa %1.2f\n', term,i)
plot(i,term,'o')
end
And it might be better still to plot them in a single line, so make the variable term a vector and plot it after the loop:
figure();
i_vector = 0.05:0.05:0.95;
for i = 1:numel(i_vector)
term(i) = F*((1/(1-i_vector(i)))^0.8+11*(1/i_vector(i))^.4);
fprintf('Cost is %4.1f for Xa %1.2f\n', term(i), i_vector(i))
end
plot(i_vector,term)
0 Comments
More Answers (1)
David Hill
on 29 Jul 2022
No for-loop needed.
i = .05:.05:.95;
F = 10;
term = F*((1./(1-i).^1).^.8+11*(1./i).^.4);
plot(term)
0 Comments
See Also
Categories
Find more on Annotations in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!