Convert binary column vector to decimal
Mostrar comentarios más antiguos
I'm trying to convert each column of a matrix A of ones and zeros to their corresponding decimal value and sort the decimal values in a new (1xn) matrix B. For eg. A=[100;011,101] B=[5 2 3] This is for a matrix A of size 52x15 and matrix B of size 1x15.
Respuesta aceptada
Más respuestas (2)
Note that A=[100;011,101] generates an error in MATLAB due to inconsistent dimensions. Perhaps you meant [100;011;101]? It is also important to realize that this defines decimal numbers 100, etc, not a list of binary digits. This means you are limited to about 15 digits (if using the default double data class). A better solution is to store the digits separately, either in a numeric or a char array.
If you store the digits as decimal numbers, try this code:
>> A = [100,011;101,111];
>> B = strjust(char(arrayfun(@(n)sprintf('%d',n),A(:), 'UniformOutput',false)))-'0';
>> B(B<0) = 0;
>> C = reshape(sum(bsxfun(@pow2,B,size(B,2)-1:-1:0),2),size(A))
C =
4 3
5 7
If you really do have a matrix of binary digits, not decimal numbers as shown in the question, then you can use this much simpler version:
D = [1,0,0;0,1,1;1,0,1;1,1,1]; % each row = one binary number
E = sum(bsxfun(@pow2,D,size(D,2)-1:-1:0),2);
F = ['100';'011';'101';'111']; % each row = one binary number
G = sum(bsxfun(@pow2,F-'0',size(F,2)-1:-1:0),2);
James Tursa
el 11 de Feb. de 2015
If I understand your question, A is a numeric 52 x 15 matrix consisting of 1's and 0's. For that case you can use:
B = bin2dec(char(A'+'0'))'
If A is actually char data and not numeric, then it is just:
B = bin2dec(A')'
I don't understand what your comment "sort the decimal values" means, since your given result B is not sorted. Maybe you meant to type "store the decimal values"?
3 comentarios
laurie
el 11 de Feb. de 2015
James Tursa
el 12 de Feb. de 2015
OK, I don't care about the Accepted Answer points, but I am curious why you accepted the double-for-loop solution which explicitly converts each digit separately instead of my one-liner solution which does everything at once?
Eduardo Márquez
el 12 de Feb. de 2015
I'm new user, I think that seek to understand how the code works, as you say your answer is more efficient, but being new user would not understand at all.
Sorry, my English is not that great.
Categorías
Más información sobre Shifting and Sorting Matrices en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!