How to save all values generated by a for loop into an array?

조회 수: 5 (최근 30일)
Sarfraz Khan
Sarfraz Khan 2019년 12월 28일
답변: Star Strider 2019년 12월 28일
Please help! I have been trying to save the numerical value of each 'counter' function but as it is in a for loop the value for counter is overwritten each time? I have copied the code below:
for n=1:100
die1= randi(6);
die2 = randi(6);
dicesum = die1+die2;
counter=0;
while dicesum<12
counter = counter+1;
die1 = randi(6);
die2 = randi(6);
dicesum = die1+die2;
end
counter
end

채택된 답변

Star Strider
Star Strider 2019년 12월 28일
Subscript it:
counterv = nan(1,100);
for n=1:100
die1= randi(6);
die2 = randi(6);
dicesum = die1+die2;
counter=0;
while dicesum<12
counter = counter+1;
die1 = randi(6);
die2 = randi(6);
dicesum = die1+die2;
end
counterv(n) = counter
end
I am not excatly certain what you want to do or how your code is organised. This saves the value of ‘counter’ in every iteration as an element of ‘counterv’ (counter vector).
Make appropriate changes so the code does what you want it to do.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by