MATLAB: Converting binary like table but using decimal values

dec2baselognMATLAB

I'm trying to create a table that will start at a negative value and increment by one in the right most column and each column to the left will only increment when there is a carry. This is similar to a binary table or any other base-n table, but I would like to keep the values in decimal format, not alpha-numeric.
I had this code which was working well, but fails if I make 'n' > 5 due to the alpha-numerics once the decimal value reaches '10'.
m = 3; %Number of signals
n = n+1; %Number of harmonics
%% Harmonic Basis Matrix
T = zeros((2*n-1)^m,m);
for k = 1:(2*n-1)^m
T(k,:) = dec2base(k-1,2*n-1,m)-num2str(n-1);
end
When I subtract num2str(n-1) from the string '00A', the result is double('00A') = 17 – double('0') = 5 ==> 17-5 = 12.
I thought about creating the matrix in alpha-numeric string form and just splitting the values into columns, but couldn't figure out how to do that effectively without using cells – which I need to avoid as this will be used in some matrix algebra.
Please note, that the variables 'm' and 'n' are part of a function input and could be completely arbitrary.
Thanks for the help!

Best Answer

  • You can use comma-separated lists on the output of ndgrid:
    >> m = 4;
    >> C = cell(1,m);
    >> [C{:}] = ndgrid(-2:2);
    >> C = cellfun(@(a)a(:),C,'uni',0);
    >> T = [C{end:-1:1}]
    ans =
    -2 -2 -2 -2
    -2 -2 -2 -1
    -2 -2 -2 0
    -2 -2 -2 1
    -2 -2 -2 2
    -2 -2 -1 -2
    -2 -2 -1 -1
    -2 -2 -1 0
    -2 -2 -1 1
    -2 -2 -1 2
    -2 -2 0 -2
    -2 -2 0 -1
    -2 -2 0 0
    -2 -2 0 1
    -2 -2 0 2
    ... lots of lines here
    2 2 1 1
    2 2 1 2
    2 2 2 -2
    2 2 2 -1
    2 2 2 0
    2 2 2 1
    2 2 2 2