I'm trying to find a path of least resistance using a matrix c of resistance and a given exogenous vector kOne of the total least resistance from point(n) to point(4) (the destination):

c={{inf, 5, 2, inf}, 
   {inf, inf, 1, inf}, 
   {inf, inf, inf, 2}, 
   {inf, inf, inf, 0}}


Using this I want to find the variable kTwo[a] by minimizing the following function:

kTwo[[a]] = min{c[[a,b]]+kOne[[b]]} subject to c[[a,b]] does not equal inf.

The point being that it should create a vector of the path of least resistance from the start to destination.

The rough code I've written so far is

n = 1;
kTwo = Range[4]; 
(*to create a vector for kTwo that I can overwrite in the while function below*)

While[n < 5,
kTwo[[n]] = Minimize[{c[[n, a]] + KOne[[a]], c[[n, a]] < Infinity}, a]; n++];

My big issue is that I get the error "expression a cannot be used as a part specification" and I'm not quite sure how to fix it so I cant really tell what else is wrong with the code. Any help or suggestions with the error or how to tackle the minimization problem would be greatly appreciated as I'm still new to Mathematica.


1 Answer 1


If I correctly understand the question, you need not reinvent the wheel - Mathematica has tools to do that. We start from forming the resistance matrix as (WL uses Infinity, not inf)

c = {{Infinity, 5, 2, Infinity}, {Infinity, Infinity, 1, 
Infinity}, {Infinity, Infinity, Infinity, 2}, {Infinity, Infinity,
 Infinity, 0}};

Next, we construct the graph gcorresponding to c by

g = WeightedAdjacencyGraph[c, VertexLabels -> "Name"]

enter image description here

Now we find shortest paths from the vertices of g to vertex 4 by

spf = FindShortestPath[g, All, 4];

and draw these paths

Table[HighlightGraph[g, PathGraph@spf[v]], {v, VertexList[g]}]

enter image description here enter image description here enter image description here enter image description here

  • $\begingroup$ Googling of "exogenous vector" brings nothing. $\endgroup$
    – user64494
    Mar 4, 2022 at 18:04
  • $\begingroup$ Thanks that'd increadibly helpful. By exogenous vector I just meant that kOne is a vector that is already given, in this case it provides the total of the path of least resistance from each node so kOne[[1]] = 4 because the path of least resistance from node 1 to 4 would be 4 while from node 2 to 4 would be 3. Also just to clarify, for the final output is it possible to represent the final least path of resistance from node 1 to 4 as a vector so in this case it would be {3,4} ? $\endgroup$
    – user85376
    Mar 5, 2022 at 2:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.