Filter löschen
Filter löschen

Sparse Arrays - Specific Function?

1 Ansicht (letzte 30 Tage)
Maroulator
Maroulator am 30 Nov. 2014
Bearbeitet: Mohammad Abouali am 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.

Akzeptierte Antwort

Mohammad Abouali
Mohammad Abouali am 30 Nov. 2014
Bearbeitet: Mohammad Abouali am 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;

Weitere Antworten (0)

Kategorien

Mehr zu Sparse Matrices finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by