Creating a column vector in a for loop

26 次查看(过去 30 天)
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 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