samedi 16 mai 2015

Sparse random matrix in Matlab with values in different range than [0,1]

How do I create a sparse random matrix in Matlab with a value range different from the default [0,1], say [-1,1]? Two things I've tried that obviously didn't work are:

p = 2 * sprand(5,5,0.1) - 1

which returns

>> p = -1.0000 -1.0000 -1.0000 -1.0000 -1.0000
       -1.0000 -1.0000 -1.0000 -1.0000 -1.0000  
       -1.0000 -1.0000 -1.0000 -1.0000 -1.0000
       -1.0000 -1.0000 -0.4850 -1.0000 -1.0000
        0.6814 -1.0000 -1.0000 -1.0000 -1.0000

And

p = ceil(sprand(5,5,0.1));
p(find(p)) = 2 * rand(5) - 1;
full(p)

which returns

>> ans =          0  0       0  0  0 
                  0  0       0  0  0
                  0  0       0  0  0
                  0  0  0.3112  0  0
             0.3112  0       0  0  0

I would like a solution that doesn't involve any looping and that only uses matrix manipulations or built-in Matlab functions.




Aucun commentaire:

Enregistrer un commentaire