MATLAB Answers

How to write pentadigonal matix?

25 views (last 30 days)
mathru
mathru on 22 Jul 2020
Edited: Bruno Luong on 27 Jul 2020
How to generate the following penta diagonal matrix in matlab?

Accepted Answer

Bruno Luong
Bruno Luong on 22 Jul 2020
Edited: Bruno Luong on 22 Jul 2020
Is it good now?
n = 12;
m = ceil(n / 3);
n = m*3;
A = spdiags([1 -4 1]+zeros(3,1), -1:1, 3, 3);
c = repmat({A},1,m);
A = blkdiag(c{:});
A = A + spdiags([1 1]+zeros(n,1), [-3 3], n, n);
full(A)
  7 Comments
Sindar
Sindar on 27 Jul 2020
Do you want to use the matrix multiple times in a loop or construct the matrix itself in a for loop instead of the above method?
  • If the first (e.g., solving for different U vectors), it's best to generate the matrix outside the loop, then call or copy it inside:
...
A = A + spdiags([1 1]+zeros(n,1), [-3 3], n, n);
for ind=1:5
% if you use the same matrix each loop
U = rand(1,9);
x{ind} = A*U;
% if you need to adjust the matrix each loop
B = A;
B(5) = rand(1);
y{ind} = B*U;
end
  • If the second, why? Matlab is designed to efficiently and cleanly handle matrices without loops. But, since the reason may be "it's the assignment", you need to think about the pattern of the indices. To start off:
n = 9;
% start with an empty matrix
A = zeros(n);
% loop through the rows (or columns)
for ind=1:n
% the diagonal (col = row) is always -4
A(ind,ind) = -4;
% except in certain cases (rows 3 6 9)
if mod(ind,3) ~= 0
% the column after the diagonal has a 1
A(ind,ind+1) = 1;
end
...
end
% this gets you to
A
-4 1 0 0 0 0 0 0 0
0 -4 1 0 0 0 0 0 0
0 0 -4 0 0 0 0 0 0
0 0 0 -4 1 0 0 0 0
0 0 0 0 -4 1 0 0 0
0 0 0 0 0 -4 0 0 0
0 0 0 0 0 0 -4 1 0
0 0 0 0 0 0 0 -4 1
0 0 0 0 0 0 0 0 -4
p.s. sorry, I also missed the gaps for my earlier answer. Depending on the situation, an alternate strategy is to make the simple matrix with consistent diagonals, then adjust the outlier elements, something like this:
n = 9;
% simple matrix
A = full(spdiags([1 1 -4 1 1]+zeros(n,1), [-3 -1:1 3], n, n));
% set to zero the elements in row-3/col-4, row-6/col-7, etc.
A(sub2ind([n n],[3 6 4 7],[4 7 3 6])) = 0

Sign in to comment.

More Answers (1)

Bruno Luong
Bruno Luong on 27 Jul 2020
Edited: Bruno Luong on 27 Jul 2020
m = 4;
n = 3*m;
T = diag(ones(1,n-3),3);
A = T + T';
B = ones(3)-5*eye(3);
A = A + kron(eye(m),B)
  1 Comment
Bruno Luong
Bruno Luong on 27 Jul 2020
If you insist on for loop
m = 4;
n = 3*m;
T = diag(ones(1,n-3),3);
A = T + T';
B = ones(3)-5*eye(3);
for k=1:m
i = (k-1)*3+(1:3);
A(i,i) = B;
end
A

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!