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

采纳的回答

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