# How can I create a new matrix which stores the diagonals, but it first starts with a matrix full of zeros?

1 vue (au cours des 30 derniers jours)
Jonas Morgner le 4 Mai 2022
Commenté : Jonas Morgner le 4 Mai 2022
%A
rng('default')
r2 = randi(100,3,3); % Creating a 3x3 matrix, with random values from 1 to 100
%B
d = diag(r2) % Obtain the diagonal elements
%C
Metod1 = d(2,1) % Using two parameters (row 2, column 1)
Metod2 = d(3) % Using one parametr (3rd element)
How can I create a new matrix (3x3) which stores the diagonals, but it first starts with a matrix full of zeros?
##### 1 commentaireAfficher -1 commentaires plus anciensMasquer -1 commentaires plus anciens
Jonas le 4 Mai 2022
so you want a zeros matrix with random diagonal elements?
diag(randi(100,3,1))

Connectez-vous pour commenter.

### Réponse acceptée

Chunru le 4 Mai 2022
n=3;
a = zeros(3)
a = 3×3
0 0 0 0 0 0 0 0 0
% random entries along diagonal
a(1:n+1:n*n) = randi(100, [n 1])
a = 3×3
22 0 0 0 87 0 0 0 57
% alternatively
a = diag(randi(100,[n,1]))
a = 3×3
41 0 0 0 86 0 0 0 96
##### 1 commentaireAfficher -1 commentaires plus anciensMasquer -1 commentaires plus anciens
Jonas Morgner le 4 Mai 2022
Thank you :)

Connectez-vous pour commenter.

### Catégories

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

### Community Treasure Hunt

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

Start Hunting!

Translated by