Message Boards Message Boards

0
|
4337 Views
|
2 Replies
|
5 Total Likes
View groups...
Share
Share this post:

Edit a sparse matrix?

Posted 7 years ago

Hi folks,

I try to study the spread of an epidemic on graphs. During the simulation, I would like to go through the non-zero elements of a SparseArray and delete these entries with some probability p.

n = 10; (* number of vertices *)
q = 0.75; (* rewiring probability *)
adjMat =  0.2*AdjacencyMatrix[RandomGraph[WattsStrogatzGraphDistribution[n, q]]];

I implemented the routine to do this in the following way:

Do[(* Go through all rows of the adjacency Matrix and modify them *)
 adjMat[[i]] = 
  Map[RandomChoice[{#, 1. - #} -> {1, 0}] &, adjMat[[i]]]
 , {i, 1, n}]

Afterwards, one has to make the SparseArray sparse again, to save memory:

adjMat = adjMat//SparseArray

For a graph with 1000 vertices, it takes quite some time.

Is there a more efficient way to do this?

Cheers,

Philipp

POSTED BY: Philipp Krönert
2 Replies

You could work directly on the ArrayRules:

n=30;(*number of vertices*)
q=0.75;(*rewiring probability*)
adjMat=0.2*AdjacencyMatrix[RandomGraph[WattsStrogatzGraphDistribution[n,q]]]

Do[
    entries=Most[ArrayRules[adjMat]];
    entries=Select[entries,(RandomChoice[{#[[2]],1-#[[2]]}->{True,False}])&];
    If[entries=!={},
        adjMat=SparseArray[entries,{n,n}];
        Print[MatrixPlot@adjMat];
    ,
        Break[]
    ]
 ,
    {5}
]
POSTED BY: Sander Huisman

Nice trick to combine Select and RandomChoice. This speeds up my algorithm a lot!

Thank you so much!

POSTED BY: Philipp Krönert
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract