MATLAB: Matrix construction from base n indices

base nindicesMATLABmatrix

I'm looking for an efficient way to construct the following matrix
where and are indexed from 0 to N as they would be in a base number system i.e. 000,001,…,00N,010,…,01N,…,0NN,…NNN. These indices are then 'split up' across the different functions . Written out this looks like
.
So, for example if then the final matrix is the following 27×27 matrix:
.
In practise N will probably be around 15 and the functions can be quite costly so ideally I'd like to implement a vectorised method.
Thanks in advance,
Andrew

Best Answer

Do I understand correctly, that you want e.g. for N=2:
f = [1,2; 3,4];
g = [10,20; 30,40];
h = [100,200; 300,400];
A = kron(kron(f,g),h);
Do you have the matrices f,g,h already? Then inlining kron might be efficient enough already:
N = size(f, 1);
ff = reshape(f, [1, 1, N, 1, 1, N]);
gg = reshape(g, [1, N, 1, 1, N, 1]);
hh = reshape(h, [N, 1, 1, N, 1, 1]);
N3 = N * N * N;
A = reshape(ff .* gg .* hh, [N3, N3]) % Implicit expansion, >= R2016b !!!


I'm not sure, if this is faster:
N = size(f, 1);
N2 = N*N;
N3 = N2*N;
ff = reshape(f, [1, N, 1, N]); % First KRON
gg = reshape(g, [N, 1, N, 1]);
fg = reshape(ff .* gg, [1, N2, 1, N2]); % Implicit expansion, >= R2016b !!!
hh = reshape(h, [N, 1, N, 1]); % Second KRON
A3 = reshape(fg .* hh, [N3, N3]); % Implicit expansion, >= R2016b !!!
By the way, thanks to Bruno Luong for this improved KRON method.