Hello,
I am having difficulties in converting a matrix of decimal numbers to its corresponding binary matrix. Here is the problem.
For example, we have a Matrix A;
A=[9 7 15 ; 4 14 8 ]
The range of values in matrix A is from 1 to 16 inclusive. A is in fact an N by 3 matrix. where N is a user-defined integer value. For each decimal number the corresponding binary output should have 5 bits. That is 5 bits per decimal number.
I want the output to be;
Output=[0 1 0 0 1 0 0 1 1 1 0 1 1 1 1 ; 0 0 1 0 0 0 1 1 1 0 0 1 0 0 0]
I tried using the following codes, but it did not work.
A=[9 7 16 ; 4 14 8 ]
x=dec2bin(A');
x=x'; x=str2num(x(:));
Output=x'
I obtain
Output=[ 0 1 0 0 1 0 0 1 1 1 1 0 0 0 0 0 0 1 0 0 0 1 1 1 0 0 1 0 0 0]
Can you please help me out?
Hope to hear from you very soon.
Thank you in advance.
Regards,
Amit

 Akzeptierte Antwort

Guillaume
Guillaume am 24 Nov. 2014

2 Stimmen

Nearly there. First since you want 5 bits per numbers, you need to tell it to dec2bin:
x = dec2bin(A', 5);
Then to convert a string of 0s and 1s into a matrix of 0s and 1s, just subtract '0' from the string
x = x'; x = x-'0';
It's then a matter of reshaping the output:
output = reshape(x, [], size(A, 1))'

1 Kommentar

Amit Sookun
Amit Sookun am 24 Nov. 2014
You are too good! Thank you very much Guillaume!!

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (1)

Community Treasure Hunt

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

Start Hunting!

Translated by