Use for loop with Circshift to generate Pentadiagonal matrix
1 次查看(过去 30 天)
显示 更早的评论
- I am trying to construct build a pentadiagonal matrix with the number of rows and columns correponding to n points (im using eight)
- 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
0 个评论
回答(2 个)
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
Alternatively, this is very terse.
z = zeros(1,6);
A = toeplitz([2 1 z],[2 3 z])
2 个评论
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.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!