Note. This answer mainly refers to unsigned data types. To convert to signed types, you need to follow a few additional steps, which are discussed here .
The bin2dec function is one of the options, but it requires you to change the vector to a string first. bin2dec can also be slow compared to calculating the number yourself. Here is a solution that is about 75 times faster:
>> A = [0,1,1,0,0,0,0,0,1,1,0,0]; >> B = sum(A.*2.^(numel(A)-1:-1:0)) B = 1548
To explain, A is multiplied elementwise by a vector of degrees 2 with exponents ranging from numel(A)-1 to 0 . The resulting vector is then summed to get an integer represented by a binary pattern of zeros and ones, with the first element in the array counting as the most significant bit. If you want the first element to be considered the least significant bit, you can do the following:
>> B = sum(A.*2.^(0:numel(A)-1)) B = 774
Update: You may be able to squeeze even a little more speed from MATLAB by using find to get their indices (avoiding elementwise multiplication and potentially reducing the number of exponential calculations needed) and using the pow2 function instead of 2.^... :
B = sum(pow2(find(flip(A))-1)); % Most significant bit first B = sum(pow2(find(A)-1)); % Least significant bit first
Expanding matrix solution ...
If you have many binary vectors that you want to convert to integers, the solution above can be easily changed to convert all values ββwith a single matrix operation. Suppose A is an N-by -1 2 matrix, with one binary vector per row. The following converts them all to an N-by -1 integer value vector:
B = A*(2.^(size(A, 2)-1:-1:0)).'; % Most significant bit first B = A*(2.^(0:size(A, 2)-1)).'; % Least significant bit first
Also note that all of the above solutions automatically determine the number of bits in your vector by looking at the number of columns in A