How to write pentadigonal matix?
조회 수: 8 (최근 30일)
이전 댓글 표시
How to generate the following penta diagonal matrix in matlab?
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/335244/image.png)
댓글 수: 0
채택된 답변
Bruno Luong
2020년 7월 22일
편집: Bruno Luong
2020년 7월 22일
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
Sindar
2020년 7월 27일
편집: Sindar
2020년 7월 27일
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
추가 답변 (1개)
Bruno Luong
2020년 7월 27일
편집: Bruno Luong
2020년 7월 27일
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
Bruno Luong
2020년 7월 27일
편집: Bruno Luong
2020년 7월 27일
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
참고 항목
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!