Creating a column vector in a for loop

26 ビュー (過去 30 日間)
Nicholas Fuller
Nicholas Fuller 2021 年 6 月 23 日
回答済み: Jan 2021 年 6 月 23 日
Hi everyone,
I am trying to create a column vector for the variable countB. Essentially, I am trying to store each value of countB into a column vector. Each pass of the for loop generates a new value for countB, and I want to keep track of all of those values to set up a gaussian distribution for said values.
options = ['A', 'B'];
countA = 0;
countB = 0;
for j=1:10000
newChoice = randsample(options, 1,true, [0.987, 0.013]);
if newChoice == 'A'
countA=countA+1;
else
countB=countB+1;
end
countB = countB(j, 1)
end
countA
countB
Right now the code generates a single value for countB, but I would like to have a large column vector. I'm guessing I'll need to use a nested for loop.

採用された回答

Jan
Jan 2021 年 6 月 23 日
options = ['A', 'B'];
n = 10000;
a = 0;
b = 0;
countA = zeros(n, 1);
countB = zeros(n, 1);
for j = 1:n
newChoice = randsample(options, 1,true, [0.987, 0.013]);
if newChoice == 'A'
a = a + 1;
else
b = b + 1;
end
countB(j) = b;
end
Maybe this is much easier:
n = 10000;
countB = rand(n, 1) > 0.987;
countB = cumsum(countB);

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by