Block diagonal matrix on lower diagonals

조회 수: 15 (최근 30일)
M.K.123
M.K.123 2015년 9월 14일
댓글: Stephen23 2015년 9월 15일
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