I am trying to solve the shortest path problem in Mathematica. My code looks like this so far. I first import the list.
list = Import["graph.txt", "CSV"];
Where list looks like this.
{{"node0", "node1 0.04", "node8 11.11", "node14 72.21"},
{"node1", "node46 1247.25", "node6 20.59", "node13 64.94"},
{"node2", "node66 54.18", "node31 166.80", "node45 1561.45"},
{"node3", "node20 133.65", "node6 2.06", "node11 42.43"},
for a hundred nodes.
Then I do this.
dataToMatrix[list0_] :=
Module[{q, list = list0, graph, node, igraph , dist , i},
q = Array[m, {100, 100}];
graph = ToExpression[StringSplit[#] & /@ list];
node = Table[ToExpression["node" <> ToString[i]], {i, 0, 99}];
igraph = graph /. MapThread[(#1 -> #2) &, {node, Range[1, 100]}];
dist = Select[Flatten[Module[{x}, x = #;
Join[x[[1]], #] & /@ x[[2 ;; -1]]] & /@ igraph, 1],
Length@# > 1 &];
MapThread[(#1 = #2) &, {Map[Extract[q, #] &, dist[[All, 1 ;; 2]]],
dist[[All, 3]]}];
Map[If[Not[Numberq[#]], # = "."] &, Flatten@q];
q = q /. "." -> inf;
Return[q]]
Then when I run
dataToMatrix[list]
It works fine at first.
But if I run it again anywhere else, it throws
Set::setraw:cannot assign to raw object 0.04'.
repeatedly.
How do I fix this? I need to use the result from dataToMatrix in other modules.
MapThread
was making an assignment between one numerical list and another numerical list (you might want to click it to see more of it but that can cause issues with longer expressions so save the notebook before). Search forMapThread
in your code for something strange ... $\endgroup$dist
. Look atdist
, nothing obviously weird then look atq
and notice thatm
has the color of a variable with an assigned value. $\endgroup$MapThread
to set an assignment between lists . You can use list1=list2 and then check that the variables in the lists have been assigned. $\endgroup$Thread[list1->list2]
which is easier to read. $\endgroup$