MATLAB Answers

How to create a cell array with binary numbers?

2 views (last 30 days)
Nick
Nick on 6 May 2021
Edited: James Tursa on 6 May 2021
I want to create a cell array 1000x11 of binary digits. I wrote the following code but when I run it, I get an array of {0×0 double} instead of {1x11}. What is wrong? How can I do that?
pop = cell(1000,11);
for i = 1:1000
pop{i}=randi([0 1],1,11)
end

Answers (1)

James Tursa
James Tursa on 6 May 2021
Edited: James Tursa on 6 May 2021
Your pop variable has 1000x11 = 11000 elements. Your for-loop only assigns values to 1000 of those elements (the first column). The rest are left as NULL which evaluates to 0x0 doubles. E.g., pop{i} = etc assigns that 1x11 array to a single element of pop, not spread out to 11 elements of pop.
If you want random 0 & 1 digits I would suggest you simply use a numeric or logical array instead of a cell array. E.g.,
pop = rand(1000,11) < 0.5;
Then to get at the binary digits you just need to access the rows of pop. E.g., pop(i,:) is the i'th row which contains the 11 binary digits.

Products

Community Treasure Hunt

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

Start Hunting!