Storing Data into a Matrix from a for loop

12 Ansichten (letzte 30 Tage)
Estevan Munoz
Estevan Munoz am 23 Nov. 2018
Kommentiert: madhan ravi am 23 Nov. 2018
Hello, I would like to alter my code so that every value for position is stored in a matrix rather than dispaying only the final value so I can plot them later. How would I write this out? Here's what I've got. Thanks!
position = 0;
tails = 0;
heads = 1;
for s = (1:1000)
x=randi([0 1]);
if x==tails
position = position-1;
elseif x==heads
position = position+1;
end
end

Akzeptierte Antwort

madhan ravi
madhan ravi am 23 Nov. 2018
position = zeros(1,1000);
position(1)=0;
tails = 0;
heads = 1;
for s = 2:1000
x=randi([0 1]);
if x==tails
position(s) = position(s-1)-1;
elseif x==heads
position(s) = position(s-1)+1;
end
end
  2 Kommentare
Estevan Munoz
Estevan Munoz am 23 Nov. 2018
Perfect! Thank you!
madhan ravi
madhan ravi am 23 Nov. 2018
Anytime :)

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (1)

Luna
Luna am 23 Nov. 2018
Hello Estevan,
Try this:
position = zeros(1,1000);
tails = 0;
heads = 1;
for s = (1:1000)
x=randi([0 1]);
if x==tails
position(s) = position(s)-1;
elseif x==heads
position(s) = position(s)+1;
end
end
  2 Kommentare
Estevan Munoz
Estevan Munoz am 23 Nov. 2018
Unfortunately doesn't dispaly data correctly. Matlab 1.png
Estevan Munoz
Estevan Munoz am 23 Nov. 2018
The orginal data became skewed for some reason. Matlab 2.png

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by