필터 지우기
필터 지우기

Use for loop with Circshift to generate Pentadiagonal matrix

조회 수: 1 (최근 30일)
JET
JET 2021년 11월 11일
답변: JET 2021년 11월 11일
  1. I am trying to construct build a pentadiagonal matrix with the number of rows and columns correponding to n points (im using eight)
  2. the center of the matrix should be 3 numbers [1,2,3] and I want them to shift to the right n times so that 2 is along the center of the diagonal and 1 and 3 are surrounding it, while there are 0's everywhere else
I essentially want it to be like
A=[ 0 0 0 1 2 3 0 0 0 ; 0 0 0 0 1 2 3 0 0; 0 0 0 0 0 1 2 3 0] and so on.
I have tried with
A= ones(size(n)
for i=0:length(n)
A+(i)*circshift(eye) but Im kind of stuck

답변 (2개)

DGM
DGM 2021년 11월 11일
편집: DGM 2021년 11월 11일
You ask for a pentadiagonal matrix, but what you describe has only three nonzero diagonals, and they aren't centered on the main diagonal. I'm going to assume you just want a regular tridiagonal matrix.
s = [8 8];
idx = reshape(1:prod(s),s);
A = zeros(s);
for d = 1:3
A(diag(idx,d-2)) = d;
end
A
A = 8×8
2 3 0 0 0 0 0 0 1 2 3 0 0 0 0 0 0 1 2 3 0 0 0 0 0 0 1 2 3 0 0 0 0 0 0 1 2 3 0 0 0 0 0 0 1 2 3 0 0 0 0 0 0 1 2 3 0 0 0 0 0 0 1 2
Alternatively, this is very terse.
z = zeros(1,6);
A = toeplitz([2 1 z],[2 3 z])
A = 8×8
2 3 0 0 0 0 0 0 1 2 3 0 0 0 0 0 0 1 2 3 0 0 0 0 0 0 1 2 3 0 0 0 0 0 0 1 2 3 0 0 0 0 0 0 1 2 3 0 0 0 0 0 0 1 2 3 0 0 0 0 0 0 1 2
  댓글 수: 2
JET
JET 2021년 11월 11일
these both work, although Im not sure what exactly the differences are between triadiagonal and pentadiagonal are since they look the same for the most part, the first code seems easier so I will try with that! Thanks!
DGM
DGM 2021년 11월 11일
The only difference is the number of nonzero diagonal vectors. A pentadiagonal matrix would have five instead of three. The difference really doesn't seem like much, but if you really wanted a pentadiagonal matrix with only three defined diagonals, one would have to ask what the other two are.
FWIW, toeplitz() looks like obfuscation through simplicity, but it's pretty simple if you realize that the two arguments are the first column vector and the first row vector. The rest is repetition.

댓글을 달려면 로그인하십시오.


JET
JET 2021년 11월 11일
Thank you for explaining this, after looking at the example given again, I realize that the numbers are shifting to the right from the center of the matrix and re-entering on the next row like [ 200581]--> [ 120058]-->[812005] so all of the values are present in each row . Sorry for the confusion,

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by