1

I have an array A=[1,0,1,1,1,0]. I want to convert it to a decimal number B = 101110. I have tried all the conversion functions, but couldn't find an appropriate solution.

Stewie Griffin
  • 14,889
  • 11
  • 39
  • 70

3 Answers3

4

This can be done quite simply this way:

B = sum(A.*10.^(numel(A)-1:-1:0))
B =
      101110

What it does is take each number in A and multiply it with 10^n where n corresponds to the value appropriated with that place in the vector. By taking the sum of this new vector you'll get your answer. It's the equivalent of:

1*10^5 + 0*10^4 + 1*10^3 + 1*10^2 + 1*10^1 + 0*10^0

As Luis commented, it can also be done as

B = 10.^(numel(A)-1:-1:0) * A(:);
Stewie Griffin
  • 14,889
  • 11
  • 39
  • 70
1

you can make a function

function decimal = array2dec(A)
nA = length(A);
decimal = 0;
for i = 1:nA
    decimal = decimal + A(i)*10^(nA-i);
end

save this.

>> A = [1,0,1,1,1,0];
>> dec = array2dec(A)
>> dec =
>>    101110
pku
  • 11
  • 2
0

Yet another approach. Probably not very fast, though:

base2dec(A+'0',10)
Luis Mendo
  • 110,752
  • 13
  • 76
  • 147