Nested loop to create and insert an array into a matrix

5 views (last 30 days)
In this project I've created a loop to determine the probability of 10 coin tosses using a loop. The coin is not supposed to have equal probability for heads and tails. Now this part is working and i get an array with 10 values, using a binary system where 0 = coins and 1 = tails.
Now, for a trail of a 100 people throwing the coin 10 times each, I would like to add together all the arrays into a matrix. The Idea is to have the columns of the matrix representing one persons results, so basically I want to add together all the 1x10 arrays created, and add them into a matrix. I was thinking to cover the former with a while-loop, and thus for each iteration one column is to be added to the main matrix.
But, my code seem to put the value of block(i) into the the matrix for each iteration, even though i have specified it ass all columns and all roes. Could anybody help me with the next step ?
M = 3 in the picture below in order to be able to better see the whole matrix, however the trend seen below happens for any number of M.
Abovre the image we have:
q = 0.6;
P = [q q-1];
P = [0 cumsum(P)];

Accepted Answer

Image Analyst
Image Analyst on 2 Sep 2022
You can make an array of tosses like this
P = 0.7; % Probability of throwing a head
numPeople = 100;
tossesPerPerson = 10;
tossResults = rand(tossesPerPerson, numPeople) <= P % 1 = head, 0=tail
tossResults = 10×100 logical array
1 1 1 1 0 1 0 1 1 1 1 1 1 1 1 1 1 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 1 1 0 1 1 1 1 0 1 1 1 0 1 1 1 0 0 1 1 1 1 0 1 1 1 1 1 0 0 1 1 1 0 1 1 0 0 1 0 0 1 1 0 1 1 1 0 0 1 0 0 0 0 1 0 0 0 1 0 1 0 1 1 1 1 1 1 1 1 0 1 1 1 1 0 1 0 1 1 1 1 1 1 1 1 0 1 0 1 1 1 0 1 1 1 1 0 0 1 0 0 1 1 1 0 1 1 1 0 1 0 1 1 1 1 1 1 0 0 0 1 1 1 0 1 1 1 1 0 1 1 1 1 1 0 1 1 0 1 1 1 1 1 0 1 1 0 1 1 1 1 1 1 1 0 1 1 1 1 1 0 0 1 1 1 1 0 1 1 0 0 1 1 1 1 0 1 0 1 0 1 0 0 1 1 1 1 1 1 1 0 0 1 1 0 1 0 1 1 1 0 0 1 0 0 1 1 1 1 1 0 1 0 1 1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 1 0 1 1 0 1 1 0 0 0 1 0 0 1 0 1 0 1 1 1 1 1 0 1 0 1 1 1 1 0 0 1 0 0 1 1 1 0 1 0 1 0 1 1 1 1 0 1 0 1 1 1 1 1 1 1 1 1 0 1 0 0 1 1 0 0 1 1 1 1 0 0 1 1 1 0 1 1 0 1 0 1 1 0 0 1 1 1 0 0 1 1 1 0 1 1 0 1 1 1 1 1 0 1 1 0 0 0 1 1 1 0 1 0 1 1 0 0 0 1 0 1 1 1 0 0 1 0 0 1 1 0 0 0 0 0 1 1 1 1 1 1 0 1 1 1 1 1 1 1 0 1 1 1 1 0 1 0 0 1 1 1 1 1 1 0 1 0 1 1 1 1 0 1 1 0 0 1 0 0 1 0 0 1 1 1 1 0 1 1 1 1 1 1 1 1 1 0 0 1 0 1 0 1 0 0 1 1 0 1 0 1 1 0 1 1 1 1 1 0 1 0 1 1 1 1 0 0 1 0 1 0 1 1 0 1 0 1
% Sum them all up within a row, going across all columns (people)
rowSums = sum(tossResults, 2) % Should be approximately 70 most of the time.
rowSums = 10×1
70 75 62 69 72 67 69 68 61 68

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!