Generate a large almost diagonal matrix

조회 수: 18 (최근 30일)
Zirui Zhang
Zirui Zhang 2022년 10월 29일
편집: John D'Errico 2022년 10월 29일
I want to generate a 1000x1000 matrix where the diagonals are 1 and the extries above the diagonal are -1. How do I do that? Thanks!

답변 (3개)

Matt J
Matt J 2022년 10월 29일
N=10;
A=eye(N)-diag(ones(1,N-1),1)
A = 10×10
1 -1 0 0 0 0 0 0 0 0 0 1 -1 0 0 0 0 0 0 0 0 0 1 -1 0 0 0 0 0 0 0 0 0 1 -1 0 0 0 0 0 0 0 0 0 1 -1 0 0 0 0 0 0 0 0 0 1 -1 0 0 0 0 0 0 0 0 0 1 -1 0 0 0 0 0 0 0 0 0 1 -1 0 0 0 0 0 0 0 0 0 1 -1 0 0 0 0 0 0 0 0 0 1

Matt J
Matt J 2022년 10월 29일
N=10;
e=ones(N,1);
A=spdiags([e,-e],[0,1],N,N);
full(A)
ans = 10×10
1 -1 0 0 0 0 0 0 0 0 0 1 -1 0 0 0 0 0 0 0 0 0 1 -1 0 0 0 0 0 0 0 0 0 1 -1 0 0 0 0 0 0 0 0 0 1 -1 0 0 0 0 0 0 0 0 0 1 -1 0 0 0 0 0 0 0 0 0 1 -1 0 0 0 0 0 0 0 0 0 1 -1 0 0 0 0 0 0 0 0 0 1 -1 0 0 0 0 0 0 0 0 0 1

John D'Errico
John D'Errico 2022년 10월 29일
편집: John D'Errico 2022년 10월 29일
This is commonly known as a bidiagonal matrix.
It is far and away best defined using sparse storage, as produced by spdiags, since your matrix has only 2 non-zero elements on every row.
But there would be many ways to create such a matrix. You could build it as a Toeplitz matrix. Of course, that would be full, not sparse.
n = 8; % produce an 8x8 matrix, so small enough to display here
A1 = toeplitz([1;zeros(n-1,1)],[1 -1,zeros(1,n-2)]);
A1
A1 = 8×8
1 -1 0 0 0 0 0 0 0 1 -1 0 0 0 0 0 0 0 1 -1 0 0 0 0 0 0 0 1 -1 0 0 0 0 0 0 0 1 -1 0 0 0 0 0 0 0 1 -1 0 0 0 0 0 0 0 1 -1 0 0 0 0 0 0 0 1
Or you could be glitzy, and not worry about the memory or even worry about efficiency.
A2 = ones(n);
A2 = triu(A2) - 2*triu(A2,1) + triu(A2,2);
A2
A2 = 8×8
1 -1 0 0 0 0 0 0 0 1 -1 0 0 0 0 0 0 0 1 -1 0 0 0 0 0 0 0 1 -1 0 0 0 0 0 0 0 1 -1 0 0 0 0 0 0 0 1 -1 0 0 0 0 0 0 0 1 -1 0 0 0 0 0 0 0 1
Or you could use indexing, with sub2ind.
A3 = zeros(n);
A3(sub2ind([n,n],1:n,1:n)) = 1;
A3(sub2ind([n,n],1:n-1,2:n)) = -1;
A3
A3 = 8×8
1 -1 0 0 0 0 0 0 0 1 -1 0 0 0 0 0 0 0 1 -1 0 0 0 0 0 0 0 1 -1 0 0 0 0 0 0 0 1 -1 0 0 0 0 0 0 0 1 -1 0 0 0 0 0 0 0 1 -1 0 0 0 0 0 0 0 1
Best, as I said, is to use spdiags, since this really is a bi-diagonal matrix. Create it using a tool designed to produce banded matrices. Matt showed you how.

카테고리

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

태그

Community Treasure Hunt

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

Start Hunting!

Translated by