Use for loop with Circshift to generate Pentadiagonal matrix

1 次查看(过去 30 天)
  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