How to use diag() once and change values after certain element?

조회 수: 2 (최근 30일)
arthurk
arthurk 2020년 2월 24일
편집: the cyclist 2020년 2월 24일
For example:
for i = 1:3
matrix(i,i) = diag(2);
matrix(i,i+1) = diag(1);
matrix(i+1,i) = diag(-1);
end
matrix(4,4) = 2;
This outputs
2 1 0 0
-1 2 1 0
0 -1 2 1
0 0 -1 2
So a simpler way of doing the above, use diag() to give a n x n matrix (n being something you choose to be), where the 0th diagonal has 2s, the 1st diagonal has 1s and the -1st diagonal has -1s
For the latter half of my question.
Can you tell where diag() to stop at ?
Basically do diag(2,0) until cell (2,2) and then after that do diag(1,0) for the same matrix. So end result is:
2 0 0 0
0 2 0 0
0 0 1 0
0 0 0 1

채택된 답변

the cyclist
the cyclist 2020년 2월 24일
편집: the cyclist 2020년 2월 24일
A simple way to construct the exact matrix in your first part is
matrix = 2*eye(4) + diag([-1 -1 -1],-1) + diag([1 1 1],1)
How you want to generalize this will depend on the specifics of your problem.
I think the blkdiag command will be helpful for the second part.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Operating on Diagonal Matrices에 대해 자세히 알아보기

제품


릴리스

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by