Reputation: 2299
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?
Upvotes: 2
Views: 277
Reputation: 112659
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.
Upvotes: 5
Reputation: 2802
I am assuming that you have the decimal place in there to slow that you want powers less than 1. Here is a brute force loop to do it.
C = 0;
for x = 1:n
C = res + A(x) * 4 ^ (-x);
end
C = 0.399999999994179
Here is another way
exp = (-1 * (1:18))';
C = sum(A .* 4 .^ exp);
C = 0.399999999994179
Using your link as a guide let's look at the number in decimal of 15
. This corresponds to the base 4 of 33
. In this case A = [3 3]
and exp = [1 0]
. This results in:
A = [3 3];
exp = [1 0];
C = sum(A .* 4 .^ exp);
C = 15
Your link has a link explaining the basics of conversions.
Upvotes: 2