Matrix construction from base n indices

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 27x27 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

1 Comment

If the computation of f,g,h is costly, the vectorization of the creation of the matrix is not the main problem, but vectorize f,g,h.

Sign in to comment.

 Accepted Answer

Jan
Jan on 12 Dec 2018
Edited: Jan on 12 Dec 2018
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.

1 Comment

Hi Jan,
Thanks very much for the help, that's exactly what I was looking for. For the minute the kron(kron(f,g),h) method is quick enough but once I've sorted some other problems in my code I'll try out your other suggestions.
I've also vectorised f,g,h now so everything runs quickly.
Regards,
Andrew

Sign in to comment.

More Answers (0)

Categories

Products

Release

R2018b

Asked:

on 12 Dec 2018

Commented:

on 13 Dec 2018

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!