how can i negative all value in a matrix except diagonal?

11 vues (au cours des 30 derniers jours)
arian hoseini
arian hoseini le 11 Jan 2022
Modifié(e) : Stephen23 le 11 Avr 2022
13.333 5 0 5 3.3333 0
5 27.333 4 10 3.3333 5
0 4 17.846 0 3.8462 10
5 10 0 17.5 2.5 0
3.3333 3.3333 3.8462 2.5 16.346 3.3333
0 5 10 0 3.3333 18.333

Réponse acceptée

Stephen23
Stephen23 le 11 Jan 2022
Modifié(e) : Stephen23 le 11 Avr 2022
M = [13.333,5,0,5,3.3333,0;5,27.333,4,10,3.3333,5;0,4,17.846,0,3.8462,10;5,10,0,17.5,2.5,0;3.3333,3.3333,3.8462,2.5,16.346,3.3333;0,5,10,0,3.3333,18.333]
M = 6×6
13.3330 5.0000 0 5.0000 3.3333 0 5.0000 27.3330 4.0000 10.0000 3.3333 5.0000 0 4.0000 17.8460 0 3.8462 10.0000 5.0000 10.0000 0 17.5000 2.5000 0 3.3333 3.3333 3.8462 2.5000 16.3460 3.3333 0 5.0000 10.0000 0 3.3333 18.3330
Method one: subtraction (square only):
A = diag(diag(M)) - M.*~eye(size(M))
A = 6×6
13.3330 -5.0000 0 -5.0000 -3.3333 0 -5.0000 27.3330 -4.0000 -10.0000 -3.3333 -5.0000 0 -4.0000 17.8460 0 -3.8462 -10.0000 -5.0000 -10.0000 0 17.5000 -2.5000 0 -3.3333 -3.3333 -3.8462 -2.5000 16.3460 -3.3333 0 -5.0000 -10.0000 0 -3.3333 18.3330
Method two: indexing (more robust, should work for any size):
B = -M;
B(eye(size(M))==1) = diag(M)
B = 6×6
13.3330 -5.0000 0 -5.0000 -3.3333 0 -5.0000 27.3330 -4.0000 -10.0000 -3.3333 -5.0000 0 -4.0000 17.8460 0 -3.8462 -10.0000 -5.0000 -10.0000 0 17.5000 -2.5000 0 -3.3333 -3.3333 -3.8462 -2.5000 16.3460 -3.3333 0 -5.0000 -10.0000 0 -3.3333 18.3330

Plus de réponses (1)

Jon
Jon le 11 Jan 2022
Am = -(A - diag(diag(A))) + diag(diag(A))

Catégories

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

Produits


Version

R2016b

Community Treasure Hunt

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

Start Hunting!

Translated by