Plotting a variable as a function of the iteration number in a for loop

8 ビュー (過去 30 日間)
Mike Scott
Mike Scott 2011 年 4 月 11 日
Hi,
Basically I have loop, within which is a 12X12 array of zeros and ones. For each cycle of the loop I need to sum the value of the array(which I am able to do) and then plot this value against the iteration/loop number.
Obviously the value of the array changes for each loop so I am a bit stuck as to how to plot the graph.
Eg. Do I output the values for each loop to a seperate new array/file, which I then draw upon at the end of the loop to create the graph? Or is there some way to construct a graph in stages as the program loops-essentially holding the plot figure and adding new points to the existing plot for each iteration.
Any help would be very much appreciated! If I have not explained very well just let me know and I can try and explain further/provide code snippets.
Thanks in advance,
Mike Scott

採用された回答

Matt Fig
Matt Fig 2011 年 4 月 11 日
Here is an example. Note that if your loop index is 1-to-N, then you won't need the loop counter and this can be simplified in obvious ways. I do have to wonder, however, if you can avoid the loop altogether. Only a look at your code can shed light here...
lp_idx = 10:.5:30; % This is the loop index.
S = zeros(1,length(lp_idx)); % Pre-allocation.
cnt = 1; % Loop counter.
for ii = lp_idx
t = magic(ii); % An array which changes in loop
S(cnt) = sum(t(:)); % The sum of each array
cnt = cnt + 1; % Increment the counter.
end
plot(lp_idx,S) % Plot sum vs. loop index
xlabel('Loop Index')
ylabel('Matrix Sum')
  5 件のコメント
Matt Fig
Matt Fig 2011 年 4 月 11 日
Note that sum(T(:)) is preferred over sum(sum(T)).
Mike Scott
Mike Scott 2011 年 4 月 11 日
Wow I have been reading through so many topics without any luck. That's great, thanks so much for your response Matt.
Much appreciated,
Mike

サインインしてコメントする。

その他の回答 (1 件)

vega valentine
vega valentine 2011 年 4 月 11 日
don't you just have to plot it outside the loop? I think what you need to do is just store every values you needed in every loop into a separate array/variable, and then after the looping is done, you can plot that array/variable.
  2 件のコメント
Mike Scott
Mike Scott 2011 年 4 月 11 日
Yes, the plot command is written outside of the loop. You have cleared up my query regarding whether to store the values as the program loops into a seperate array, which makes sense now. Is there a command that I should use to set up this array and then assign the values generated in each loop to?
Thanks for your reply
Oleg Komarov
Oleg Komarov 2011 年 4 月 11 日
Post the code you're using, formatting with the code button.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeConway's Game of Life についてさらに検索

製品

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by