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 件のコメント

James Tursa
James Tursa 2021 年 4 月 21 日
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.
David Fletcher
David Fletcher 2021 年 4 月 21 日
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

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

回答 (1 件)

DGM
DGM 2021 年 4 月 21 日

0 投票

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')

カテゴリ

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

質問済み:

2021 年 4 月 21 日

回答済み:

DGM
2021 年 4 月 21 日

Community Treasure Hunt

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

Start Hunting!

Translated by