Block diagonal matrix on lower diagonals

12 views (last 30 days)
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!!

Accepted Answer

Stephen23
Stephen23 on 14 Sep 2015
Edited: Stephen23 on 14 Sep 2015
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.
  2 Comments
M.K.123
M.K.123 on 15 Sep 2015
Edited: M.K.123 on 15 Sep 2015
Thanks a lot! It works great!! Do you maybe also know an efficient method to save this matrix and to use it later in a backslash operator?
Stephen23
Stephen23 on 15 Sep 2015
If you want to save a variable to a file then the fastest and most efficient way is to use save:
save(filename,'A')
And the load the data later from the file:
X = load(filename);
X.A

Sign in to comment.

More Answers (0)

Categories

Find more on Operating on Diagonal Matrices in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!