Storing Data into a Matrix from a for loop
1 次查看(过去 30 天)
显示 更早的评论
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
0 个评论
采纳的回答
madhan ravi
2018-11-23
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
更多回答(1 个)
Luna
2018-11-23
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
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!