Elementary matrices in Matlab

11 ビュー (過去 30 日間)
Tim david
Tim david 2022 年 2 月 2 日
編集済み: DGM 2022 年 2 月 17 日
I am very new to MATLAB, and I am trying to create a numerical scheme to solve a differential equation. However I am having trouble implementing matrices. I was wondering if anyone can help with constructing a following NxN matrix?
I am sure there is a better way to implement, but the following works
N=10
tod=zeros(N)
for k=1:(N-1)
tod(k, k+1)=-2
end
for k=1:(N-2)
tod(k, k+2)=1
end
tod_2=zeros(N)
for k=1:(N-1)
tod_2(k, k+1)=2
end
for k=1:(N-2)
tod_2(k, k+2)=-1
end
tran=transpose(tod_2)
Final=tran+tod

回答 (3 件)

DGM
DGM 2022 年 2 月 2 日
編集済み: DGM 2022 年 2 月 17 日
(EDIT to fix misread)
Here's one way:
n = 8;
z = zeros(1,n-3);
R = toeplitz([0 2 -1 z],[0 -2 1 z])
R = 8×8
0 -2 1 0 0 0 0 0 2 0 -2 1 0 0 0 0 -1 2 0 -2 1 0 0 0 0 -1 2 0 -2 1 0 0 0 0 -1 2 0 -2 1 0 0 0 0 -1 2 0 -2 1 0 0 0 0 -1 2 0 -2 0 0 0 0 0 -1 2 0
  5 件のコメント
DGM
DGM 2022 年 2 月 3 日
Oof . I totally overlooked that.
Stephen23
Stephen23 2022 年 2 月 3 日
@DGM: add it to your answer, no one will look in these comments.

サインインしてコメントする。


John D'Errico
John D'Errico 2022 年 2 月 2 日
So many ways to do this. DGM showed a great way using toeplitz. But there are others. For example, you could use diag.
n = 5;
R = diag(ones(n-2,1),2) - 2*diag(ones(n-1,1),1); R = R + R'
R = 5×5
0 -2 1 0 0 -2 0 -2 1 0 1 -2 0 -2 1 0 1 -2 0 -2 0 0 1 -2 0
Or use spdiags, creating the matrix directly. Since your matrix is banded, if n is at all large, then you truly want to learn to use sparse matrices.
n = 10;
R = spdiags(ones(n,1)*[1 -2 -2 1],[-2 -1 1 2],n,n);
R is now a sparse matrix, so it will offer great advantages in computing when n grows large.
spy(R)
full(R)
ans = 10×10
0 -2 1 0 0 0 0 0 0 0 -2 0 -2 1 0 0 0 0 0 0 1 -2 0 -2 1 0 0 0 0 0 0 1 -2 0 -2 1 0 0 0 0 0 0 1 -2 0 -2 1 0 0 0 0 0 0 1 -2 0 -2 1 0 0 0 0 0 0 1 -2 0 -2 1 0 0 0 0 0 0 1 -2 0 -2 1 0 0 0 0 0 0 1 -2 0 -2 0 0 0 0 0 0 0 1 -2 0
I could probably have used tools like meshgrid, tril and triu.
  1 件のコメント
Voss
Voss 2022 年 2 月 2 日
This answer does not produce the requested matrix.

サインインしてコメントする。


Voss
Voss 2022 年 2 月 2 日
Here's one way you can do it (and it produces the correct matrix too):
N = 10;
R = zeros(N);
R(2:N+1:end-N) = 2;
R(3:N+1:end-2*N) = -1;
R(N+1:N+1:end-1) = -2;
R(2*N+1:N+1:end-2) = 1;
R
R = 10×10
0 -2 1 0 0 0 0 0 0 0 2 0 -2 1 0 0 0 0 0 0 -1 2 0 -2 1 0 0 0 0 0 0 -1 2 0 -2 1 0 0 0 0 0 0 -1 2 0 -2 1 0 0 0 0 0 0 -1 2 0 -2 1 0 0 0 0 0 0 -1 2 0 -2 1 0 0 0 0 0 0 -1 2 0 -2 1 0 0 0 0 0 0 -1 2 0 -2 0 0 0 0 0 0 0 -1 2 0

カテゴリ

Help Center および File ExchangeResizing and Reshaping Matrices についてさらに検索

タグ

製品


リリース

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by