Clear Filters
Clear Filters

How to plot for a loop

2 views (last 30 days)
Hi Everybody, I need to get plot of this loop, below, in an one plot. However, I am having an empty plot. How can I solve this problem? I mean that I need delta_V value for every value of 1000 on x axis. Thanks in advance.
Edit: It is surprising that when I run this script a few more times, It worked. So, why did that happen? Can you please explain?
E = 15000;
delta_p = 1000;
Vo = 7.854 ;
for i = 1:10
delta_V(i) = delta_p * Vo / E;
Vo = Vo - delta_V(i);
end
figure
plot(1000:1000:10000,delta_V)
title('Compression Ratio')
xlabel('Pressure Change')
ylabel('Volume Change')
hold on

Accepted Answer

sloppydisk
sloppydisk on 7 May 2018
Edited: sloppydisk on 7 May 2018
This should work just fine, although I would suggest using
figure(1)
instead of
figure
, which makes a new figure on every run. This is probably what caused you to see an empty figure at some point.
Also for good practice preallocate delta_V before the for loop:
V = zeros(1, 10);
And you don't need the hold on in this case, because you aren't plotting multiple lines in one figure.
  3 Comments
sloppydisk
sloppydisk on 7 May 2018
Edited: sloppydisk on 7 May 2018
Probably because this is a very small loop so it is not really necessary, but I would still do it to get used to it. Here the time gained by not dynamically expanding the array is apparently smaller than the time lost by preallocating. Try increasing the number of elements to 10000, then you should see it being a lot faster.
Ender Rencuzogullari
Ender Rencuzogullari on 7 May 2018
I got it now, thank you.

Sign in to comment.

More Answers (0)

Categories

Find more on Line Plots 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!