Plotting each iteration of a while loop

So the code is first supposed to create a 1x10 array of 0's and 1's. It is then supposed to convert that binary number to a decimal. Then that decimal number is supposed to be cut in half until it is less than 1. I need to find the number of iterations to become less than one. Then I need to plot the values of each iteration vs the iteration #. The code correctly gives me the number of iterations but I can't get it to plot. It just gives me a blank plot. Thanks
clear all
close all
clc
r = randi(([0 1]),1,10);
disp(r)
sr = num2str(r);
dec=bin2dec(sr);
disp(dec)
count = 0;
while(dec>1)
dec = dec/2;
count = count +1;
figure(2)
plot(count,dec)
ylim([0 1000]);
xlim([ 0 10]);
hold on
end
display(count);

回答 (1 件)

Sebastian Castro
Sebastian Castro 2017 年 10 月 9 日

1 投票

The easiest thing would be to use the hold command to prevent the plot being overwritten every time you call plot. The general code structure would be:
figure
hold on
while CONDITION
plot(STUFF)
end
For more information, check the documentation at https://www.mathworks.com/help/matlab/ref/hold.html.
The other thing to note is that the default plot style is a line with no markers... so if you want to plot individual points one at a time, then for example you can do them as red circular markers:
plot(STUFF,'ro');
- Sebastian

1 件のコメント

Ridwan Shahidul
Ridwan Shahidul 2020 年 4 月 16 日
Lets say i want the first 100 samples from my while loop to be plotted, how would I go about making that happen?

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

カテゴリ

ヘルプ センター および File ExchangeLoops and Conditional Statements についてさらに検索

質問済み:

2017 年 10 月 9 日

コメント済み:

2020 年 4 月 16 日

Community Treasure Hunt

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

Start Hunting!

Translated by