2
$\begingroup$

I have something like this

edgesList = {{1, 3}, {1, 5}, {2, 1}, {2, 6}, {5, 2}, {5, 6}, {6, 1}, {6, 4}}

And I need something like this as output.

{Subscript[x, 1 \[RightArrow] 3] + Subscript[x, 1 \[RightArrow] 5] - 
  Subscript[x, 2 \[RightArrow] 1] - Subscript[x, 6 \[RightArrow] 1], 
 Subscript[x, 2 \[RightArrow] 1] + Subscript[x, 2 \[RightArrow] 6] - 
  Subscript[x, 5 \[RightArrow] 2], -Subscript[x, 
  1 \[RightArrow] 3], -Subscript[x, 
  6 \[RightArrow] 4], -Subscript[x, 1 \[RightArrow] 5] + Subscript[x, 
  5 \[RightArrow] 2] + Subscript[x, 
  5 \[RightArrow] 6], -Subscript[x, 2 \[RightArrow] 6] - Subscript[x, 
  5 \[RightArrow] 6] + Subscript[x, 6 \[RightArrow] 1] + Subscript[x, 
  6 \[RightArrow] 4]}

I have accomplished this in procedural way, but I'm curious how to make it functional.

equations = Array[0 &, nVertexes];
For[i = 1, i <= nEdges, i++, 
  equations[[edgesList[[i, 1]]]] = 
   equations[[edgesList[[i, 1]]]] + 
    Subscript[x, edgesList[[i, 1]] \[RightArrow] edgesList[[i, 2]]]; 
  equations[[edgesList[[i, 2]]]] = 
   equations[[edgesList[[i, 2]]]] - 
    Subscript[x, edgesList[[i, 1]] \[RightArrow] edgesList[[i, 2]]];];
$\endgroup$

2 Answers 2

5
$\begingroup$
Clear[x]
equations = Array[0 &, 6];
edgesList = {{1, 3}, {1, 5}, {2, 1}, {2, 6}, {5, 2}, {5, 6}, {6, 
    1}, {6, 4}};
Fold[With[{i = First@#2, j = Last@#2}, ReplacePart[#1,
    {i -> #1[[i]] + Subscript[x, i \[RightArrow] j],
     j -> #1[[j]] - 
       Subscript[x, i \[RightArrow] j]}]] &, equations, edgesList]
$\endgroup$
1
  • $\begingroup$ So EXTREMELY sharp good solution, I really enjoyed to learn from you @Alan $\endgroup$ Commented Feb 20, 2018 at 21:56
1
$\begingroup$

Another functional way:

Table[
 If[#1 == j, 1, -1] Subscript[x, #1 -> #2] & @@@ Select[edgesList, MemberQ[#, j] &] // Total,
 {j, 1, Max@Flatten@edgesList}]
$\endgroup$

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.