Creating a column vector in a for loop

26 Ansichten (letzte 30 Tage)
Nicholas Fuller
Nicholas Fuller am 23 Jun. 2021
Beantwortet: Jan am 23 Jun. 2021
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.

Akzeptierte Antwort

Jan
Jan am 23 Jun. 2021
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);

Weitere Antworten (0)

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