Reputation: 715
I have a piece of code which outputs what I want but in the wrong format
for k=1:100
bin(k,:)=dec2bin(randi([0 31]),5);
end
I want the output to be a 100x5 double array, with one bit per cell (0 or 1 value).
I've tried using the double()
function...
for k=1:100
bin(k,:)=double(dec2bin(randi([0 31]),5));
end
...but that returns the correct format, with the wrong values.
My jargon might be a bit off, I apologise (Am I using cell, double, etc in the wrong context?)
Thank you for helping me.
Upvotes: 2
Views: 400
Reputation: 32920
There are a lot of ways to do what you want. The simplest would actually be generating the binary array right from the start, without a loop:
bin = rand(100, 5) > 0.5
Other alternatives:
If you have an integer array and you want to convert it to bits, you can use bitget
instead of dec2bin
inside the loop:
bin(k, :) = bitget(randi([0 31]), 5:-1:1)
If you already have a string array representing binary numbers, and you want to operate on it, you can delimit the bits with spaces and then apply str2num
:
bin = reshape(str2num(sprintf('%c ', bin)), size(bin))
Upvotes: 2