Plotting problem and while loops

I am having an issue with plotting my code using a while loop. I want it to show a negative downward line with the y-axis ranging from 0 to 50 and the x-axis ranging from 1 to whatever the maximum number of days it is. When I plot it, the y-axis goes from 1 to -1 in increments of -0.2, and the x-axis goes from 6 to 8 in increments of 0.5. The line doesn't even show up when I zoom out. I am unsure of what I am doing wrong. Any idea on how to fix this?
clear;clc
MandM = 50;
day = 1;
while MandM > 0
day = day + 1
MandM = MandM - randi(3)
MandM = MandM - 7
end
MandM = 0
plot(day,MandM)
xlabel('day')
ylabel('M&Ms remaining')

2 Comments

Please delete the image and post your code as text highlighted with the CODE button instead. We can't copy & run images at our end.
You need to save each value of MandM in the loop - and having gone to the effort of doing that, preferably not overwrite it with 0 when the loop ends

Sign in to comment.

Answers (1)

Something like this:
% initial conditions
MandM = 50;
day = 1;
while MandM > 0
% operate on the last element of the vector and append the result
day = [day day(end) + 1];
MandM = [MandM (MandM(end) - randi(3) - 7)];
end
plot(day,MandM)
xlabel('day')
ylabel('M&Ms remaining')

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Asked:

on 21 Apr 2021

Answered:

DGM
on 21 Apr 2021

Community Treasure Hunt

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

Start Hunting!