MATLAB: Block diagonal matrix on lower diagonals

blkdiagblock diagonaldiagonalmatrixno loops

Hello I want to create a matrix which has block matrices on every diagonal. So on the first diagonal there is the matrix B(1) on the second diagonal the matrix B(2) and so on:
A =
1.0e-04 *
0.4059 0.0125 0 0 0 0 0 0
0.0125 0.4059 0 0 0 0 0 0
0.0845 0.0208 0.4059 0.0125 0 0 0 0
0.0208 0.0845 0.0125 0.4059 0 0 0 0
0.0425 0.0170 0.0845 0.0208 0.4059 0.0125 0 0
0.0170 0.0425 0.0208 0.0845 0.0125 0.4059 0 0
0.0267 0.0135 0.0425 0.0170 0.0845 0.0208 0.4059 0.0125
0.0135 0.0267 0.0170 0.0425 0.0208 0.0845 0.0125 0.4059
As this matrix can be quite large I want to avoid any loops. The main diagonal is no problem as I can use blkdiag but how can I solve the problem with the other diagonals?
Thank you a lot in advance!!

Best Answer

New Answer! Simply define a cell vector of matrices, which must all be the same size. The rest happens automagically. Some fake data:
B{1} = [0,1;2,3];
B{2} = [4,5;6,7];
B{3} = [8,9;10,11];
B{4} = [12,13;14,15];
Create numeric matrix A with the elements of B on the diagonals:
N = numel(B);
X = tril(true(N));
Y = hankel(ones(1,N));
[R,C] = find(Y);
U = accumarray(R,find(X),[],@(n){n});
Z = cell(N);
for k = 1:N
Z(U{k}) = B(k);
end
Z(~X) = {zeros(size(B{1}))};
A = cell2mat(Z);
And the example output array:
>> A
A =
0 1 0 0 0 0 0 0
2 3 0 0 0 0 0 0
4 5 0 1 0 0 0 0
6 7 2 3 0 0 0 0
8 9 4 5 0 1 0 0
10 11 6 7 2 3 0 0
12 13 8 9 4 5 0 1
14 15 10 11 6 7 2 3
Yes it has a loop, but only a small one that loops once over the elements of B.