Clear Filters
Clear Filters

Sparse Arrays - Specific Function?

1 view (last 30 days)
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.

Accepted Answer

Mohammad Abouali
Mohammad Abouali on 30 Nov 2014
Edited: Mohammad Abouali on 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;

More Answers (0)

Categories

Find more on Sparse Matrices in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!