Search code examples
matlabmathradix

Convert a non-integer in base d to a number in base 10 in Matlab


I have a column vector t of dimension nx1 in Matlab reporting the digits after the comma of a number A in base d. I want to convert it in a 1x1 double reporting the number A in base 10. I am interested in the cases d=2 and d=3.

Example

%d=3
t=[0 2 0 2 2 0 0 2 0]'; %that is A=0.020220020 in base 3
%d=2
t=[0 1 1 1 0 0 0 1 0]'; %that is A=0.011100010 in base 2

Solution

  • A = base2dec(char(t(:).'+'0'), d) / d^numel(t);
    

    This works as follows:

    1. Treat the digits as if they were to the left of the decimal mark, thus defining an integer in base d. That way you can use base2dec for the conversion (note that the input to this function needs to be char).
    2. Divide by the appropriate power of d to take into account that the input digits actually are to the right of the decimal mark.

    For example, given

    t = [0 2 0 2 2 0 0 2 0]';
    d = 3;
    

    the result is

    A =
       0.255448864502362