I am writing a Matlab code for a solution to a non-linear partial differential equations. I reached a point where I need an (M+1)^2 by (M+1)^2 block matrix containing say A as the main diagonal, B in position (i,i+1) while C in (i,i+2). i.e., B and C are above the main diagonal A. Is there a short way to build such block matrices?
1 Answers
1
votes
To begin with, you can build a single block using triu function like this:
M = 4;
A = 2; B = 3; C = 4;
onesMat = ones(M+1,M+1);
block = A*eye(M+1) + B*(triu(onesMat,1)-triu(onesMat,2)) + C*(triu(onesMat,2)-triu(onesMat,3));
block =
2 3 4 0 0
0 2 3 4 0
0 0 2 3 4
0 0 0 2 3
0 0 0 0 2
If my understanding is correct and you want to create a block-diagonal matrix by repeating the same block M+1
times, you can use blkdiag
for that:
blocks = repmat({block}, M+1, 1);
res = blkdiag(blocks{:});