フィルターのクリア

How to write pentadigonal matix?

5 ビュー (過去 30 日間)
mathru
mathru 2020 年 7 月 22 日
編集済み: Bruno Luong 2020 年 7 月 27 日
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 Center および File ExchangeSparse Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by