Sparse Arrays - Specific Function?

1 次查看(过去 30 天)
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.

采纳的回答

Mohammad Abouali
Mohammad Abouali 2014-11-30
编辑:Mohammad Abouali 2014-11-30
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;

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Sparse Matrices 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by