フィルターのクリア

How do I repeat a for loop for all columns?

1 回表示 (過去 30 日間)
Bianca Batista
Bianca Batista 2018 年 5 月 7 日
回答済み: Jan 2018 年 5 月 7 日
I have a for loop that runs through all of my 1,000 rows. The next step is to get this code to run exactly the same way but for each of the 10,000 columns. I don't know if there is a simple way to do this--I tried adding "for j=1:n_trials" but that didn't seem to work. Any help is appreciated. Thanks!
n_steps = 1000 n_trials = 10,000 x_pos = zeros(n_steps,n_trials);
for i=2:n_steps
direction=rand;
if direction < 0.3
x_pos(i) = x_pos(i-1)+1;
elseif (0.3 < direction) && (direction < 0.5)
x_pos(i)=x_pos(i-1)-1;
else
x_pos(i)=x_pos(i-1);
end
end

採用された回答

Akbar
Akbar 2018 年 5 月 7 日
編集済み: Akbar 2018 年 5 月 7 日
Try this. You should use two arguments (i,j) i=row number. j=column number. And one more "for" Loop, for the columns.
n_steps = 1000;
n_trials = 10000;
x_pos = zeros(n_steps,n_trials);
for i=2:n_steps
for j = 1:n_trials
direction=rand;
if direction < 0.3
x_pos(i,j) = x_pos(i-1,j)+1;
elseif (0.3 < direction) && (direction < 0.5)
x_pos(i,j)=x_pos(i-1,j)-1;
else
x_pos(i,j)=x_pos(i-1,j);
end
end
end

その他の回答 (1 件)

Jan
Jan 2018 年 5 月 7 日
With a vectorized approach:
n_steps = 1000;
n_trials = 10000;
x_pos = zeros(n_steps, n_trials);
for k = 2:n_steps
direction = rand(1, n_trials);
step = zeros(1, n_trials);
step(direction <= 0.3) = 1;
step((0.3 < direction) && (direction < 0.5)) = -1;
x_pos(k, :) = x_pos(k-1, :) + step;
end
I've modified one condition from < 0.3 to <= 0.3, such that direction==0.3 is caught also.

カテゴリ

Help Center および File ExchangeLegend についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by