How to write pentadigonal matix?

5 次查看(过去 30 天)
How to generate the following penta diagonal matrix in matlab?

采纳的回答

Bruno Luong
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 个评论
mathru
mathru 2020-7-27
How can I write this matrix using for loop?
Sindar
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
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
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

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Sparse Matrices 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by