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

2 vues (au cours des 30 derniers jours)
arthurk
arthurk le 24 Fév 2020
Modifié(e) : the cyclist le 24 Fév 2020
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

Réponse acceptée

the cyclist
the cyclist le 24 Fév 2020
Modifié(e) : the cyclist le 24 Fév 2020
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.

Plus de réponses (0)

Catégories

En savoir plus sur Operating on Diagonal Matrices dans Help Center et File Exchange

Produits


Version

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by