2010-04-22 37 views
10

I tiene una matriz de enteros:Entero matriz a matriz binaria

a=[3,4,5,6,7]; 

Quiero convertirla en una matriz binaria con cuatro bits cada uno. Para el arreglo de enteros por encima me gustaría obtener la siguiente matriz binaria:

abinary=[0,0,1,1, 0,1,0,0, 0,1,0,1, 0,1,1,0, 0,1,1,1]; 

¿Hay alguna forma rápida de hacerlo?

Respuesta

16

Matlab tiene la función incorporada DEC2BIN. Crea una matriz de caracteres, pero es fácil volver a los números.

%# create binary string - the 4 forces at least 4 bits 
bstr = dec2bin([3,4,5,6,7],4) 

%# convert back to numbers (reshape so that zeros are preserved) 
out = str2num(reshape(bstr',[],1))' 
+0

Muchas gracias Jonas !! ;) – asel

4

Usted puede utilizar la función BITGET:

abinary = [bitget(a,4); ... %# Get bit 4 for each number 
      bitget(a,3); ... %# Get bit 3 for each number 
      bitget(a,2); ... %# Get bit 2 for each number 
      bitget(a,1)];  %# Get bit 1 for each number 
abinary = abinary(:)';  %'# Make it a 1-by-20 array 
+0

Ni siquiera sabía sobre bitget. Me gustaría hacer un bucle para construir abinary, sin embargo, para poder usar esto para cualquier cantidad de bits. +1 de todos modos. – Jonas

1

Una respuesta tardía lo sé, pero MATLAB tiene una función para hacer esto directamente de2bi

out = de2bi([3,4,5,6,7], 4, 'left-msb'); 
+0

'de2bi' solo está disponible en [Communications System Toolbox] (https://uk.mathworks.com/help/comm/ref/de2bi.html). Existe una función similar 'decimalToBinaryVector' en [Data Acquisition Toolbox] (https://uk.mathworks.com/help/daq/ref/decimaltobinaryvector.html). – nekomatic

Cuestiones relacionadas