I want to convert n integers to base b, and write every digit as a single number in a matrix.
I get the base b representation with:
stringBaseB=dec2base(0:1:1000,b,10)
but don't know how to split every string into a single char
[[0,0,0,0];[0,0,0,1];[0,0,0,2];...]
I can use array2table to split the individual characters:
tableBaseB=array2table(dec2base(stringBaseB,b,10))
but that's not a numeric matrix. Also, in base b>10 I get alphanumeric characters, which I need to convert to numeric by an equivalence like
alphanumeric=["1","A","c","3"]
numericEquivalence=[1,1 i,-3,0]
There is a vectorized way to do it?
CodePudding user response:
For some base b < 11
, where the character array from dec2base
is always going to be single-digit numeric characters, you can simply do
b = arrayfun( @str2double, stringBaseB );
For some generic base b
, you can make a map between the characters and the values (your numericEquivalence
)
charMap = containers.Map( {'1','2','3'}, {1,2,3} );
Then you can use arrayfun
(not strictly "vectorized" as you requested but it's unclear why that's a requirement)
stringBaseB=dec2base(0:1:1000,b,10);
b = arrayfun( @(x)charMap(x), stringBaseB );
This gives you a numeric output array, for example stringBaseB=dec2base(0:5,3,10)
gives
stringBaseB =
6×10 char array
'0000000000'
'0000000001'
'0000000002'
'0000000010'
'0000000011'
'0000000012'
b =
6x10 double array
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 1
0 0 0 0 0 0 0 0 0 2
0 0 0 0 0 0 0 0 1 0
0 0 0 0 0 0 0 0 1 1
0 0 0 0 0 0 0 0 1 2