Block diagonal matrix on lower diagonals

15 次查看(过去 30 天)
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!!

采纳的回答

Stephen23
Stephen23 2015-9-14
编辑:Stephen23 2015-9-14
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 个评论
M.K.123
M.K.123 2015-9-15
编辑:M.K.123 2015-9-15
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 2015-9-15
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

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Operating on Diagonal Matrices 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by