Plotting each iteration of a while loop

19 views (last 30 days)
Brandon Pike
Brandon Pike on 9 Oct 2017
Commented: Ridwan Shahidul on 16 Apr 2020
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);

Answers (1)

Sebastian Castro
Sebastian Castro on 9 Oct 2017
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 Comment
Ridwan Shahidul
Ridwan Shahidul on 16 Apr 2020
Lets say i want the first 100 samples from my while loop to be plotted, how would I go about making that happen?

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!