How to use diag() once and change values after certain element?
조회 수: 2 (최근 30일)
이전 댓글 표시
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
댓글 수: 0
채택된 답변
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.
댓글 수: 0
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Operating on Diagonal Matrices에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!