Search code examples
matlabradix

Converting to decimal in Matlab?


I am asking for an help to write a code doing the following in Matlab:

(1) I have a column vector A of dimension nx1 listing the n digits after the comma of a number B in base 4 between 0 and 1

What I mean by base 4 is explained here

Example

n=18
A=[1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2]' %representing B=0.121212121212121212

(2) I want to convert B to base 10 (decimal representation) and store the obtained decimal number C in a 1x1 matrix

Could you help me to understand how to do this?


Solution

  • Here's a way:

    C = base2dec(char(A(:).'+'0'), 4)*4^-numel(A);
    

    This converts the digits to an integer in base 4 and then divides by the appropriate power of 4.

    Take into account that C will be limited by double precision, so some decimals may be lost. If you want more precision you need to use symbolic variables.