1
votes

My Mathematica (both version 10.4 and the new 11) crash in the following loop:

count = 0;   

findConnectedNodes[start_] := Module[{positions, i},

count++;
positions = adjmatrix[[start]] // ArrayRules // Keys;
positions = positions[[1 ;; -2]] // Flatten;

For[i = 1, i <=  Length[positions], i++,

 If[Not[MemberQ[connectedNodes, positions[[i]]]], 
  findConnectedNodes[positions[[i]]]];

 AppendTo[connectedNodes, positions[[i]]];
 connectedNodes = connectedNodes // DeleteDuplicates;

 ]

];

findConnectedAddresses[1];

The variable adjmatrix is a SparseArray and this code is to find all connected nodes in an adjacency matrix.

Interestingly the code works very well up to about 14'000 "counts" (the variable count) and after that Mathematica just crashes.

$RecursionLimit is set to Infinity.

Thank you very much for your help. And also any other suggestions for the code are much appreciated.

2
I cannot replicate your problem on my machine. Could you please edit your code and show the input and output for a simple example. here is a sparse array: adjmatrix = SparseArray[{{i_, i_} -> 12, {i_, j_} /; Abs[i - j] == 1 -> 1}, {5, 5}] @Michael Gwerder - Conor Cosnett
You could look up Do in the documentation it has better performance than For. Also Table and ParallelTable - Conor Cosnett
you have not assigned any values to connectedNodes @Michael Gwerder - Conor Cosnett
have you looked at NeighborhoodGraph - agentp
Thanks for the inputs. connectedNodes was actually defined before, I just forgot to include into the question. The problem probably had to do with too many recursions. - Michael Gwerder

2 Answers

0
votes

Although you set the variable $RecursionLimit to infinity all programming languages can only recurse until so much. If I can assume correctly the Mathematica compiler is throwing you a "Stack Overflow" error which happens when the current local "stack memory" overflows (or surpasses) the maximum stack memory size.

Based on what I am inferring I would recommend force/manually initialise the Mathematica garbage collector at the end of each recursion to destroy the unwanted variable references created from previous recursions. If you can provide the error message given when your loop crashes, I or other people will be able to get you a more constructive or grounded response.

0
votes

Thank you very much for all the tips and ideas.

My solution was to add the new nodes that were found to a intermediate variable and loop on that variable. In that way I did not go "deeper" into the loop and always stayed at one level.

If anyone has a similar (or the same) problem I will write the whole code. But for now I hope the "text-version" is self explanatory.