Azzera filtri
Azzera filtri

Sparse Arrays - Specific Function?

1 visualizzazione (ultimi 30 giorni)
Maroulator
Maroulator il 30 Nov 2014
Modificato: Mohammad Abouali il 30 Nov 2014
I need to initialize a 100X100 sparse array with random values and a density of 5%; I then need to set all diagonal elements of that sparse array to 1. I can get the first piece of my problem using the sprand(100,100,0.05) command, but I have no idea how to do the second piece without using speye(100) which will overwrite the random values of my initial matrix.
Other than using a for loop, does anyone know of a function that will just set all diagonal elements of my 100X100 matrix to 1 without losing the random values ascribed to some of the off-diagonal elements?
Thanks in advance.

Risposta accettata

Mohammad Abouali
Mohammad Abouali il 30 Nov 2014
Modificato: Mohammad Abouali il 30 Nov 2014
s=sprand(100,100,0.05);
s(sub2ind(size(s),1:100,1:100))=1.0;
or
s=sprand(100,100,0.05);
s(1:101:(100*100))=1.0;

Più risposte (0)

Categorie

Scopri di più su Sparse Matrices in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by