2
$\begingroup$

I have a concrete function $f:V\rightarrow P(V)$ that describes the neighborhood of a vertex $g$. I tried to use FunctionalGraph[f, V] , but apparently, this function was removed from Mathematica.

So, how to generate a graph from a function?

$\endgroup$
2
  • 1
    $\begingroup$ You have to load the Combinatorica package with Needs["Combinatorica`"] before you can use FunctionalGraph. $\endgroup$ Commented Jun 20, 2019 at 14:04
  • 3
    $\begingroup$ Graph[(# <-> f[#]) & /@ v], where f is your function and v are the vertices. $\endgroup$
    – ktm
    Commented Jun 20, 2019 at 14:05

3 Answers 3

1
$\begingroup$

All you need is something like the code

ClearAll[f, V, a, b, c, d]; V = {a, b, c, d};
f[a] = {b}; f[b] = {c}; f[c] = {a, d}; f[d] = {c};
Graph[Flatten[Function[x, x -> # & /@ f[x]] /@ V]]

which returns a directed graph. A variant is to replace the last line with

Graph[Flatten[(Thread[# -> f[#]]) & /@ V]]

and there are probably a few other ways to do it.

$\endgroup$
3
  • $\begingroup$ My graph is directed, and the function returns a set of neighbors of a certain vertex. $\endgroup$ Commented Jun 20, 2019 at 19:28
  • 1
    $\begingroup$ @user2679290 Oops! I did not notice that detail. I adjusted my code to work in that case. Thanks for telling. $\endgroup$
    – Somos
    Commented Jun 20, 2019 at 19:55
  • $\begingroup$ Yeh, Thread is essentially what I do in a seperate function $\endgroup$ Commented Jun 20, 2019 at 21:36
2
$\begingroup$

You can also use RelationGraph with MemberQ[f@#, #2]& as the first argument:

Using Somos's example:

vl = {a, b, c, d};
f[a] = {b}; f[b] = {c}; f[c] = {a, d}; f[d] = {c};
RelationGraph[MemberQ[f @ #, #2]&, vl]

enter image description here

$\endgroup$
0
$\begingroup$

Well, the code is

JJ[a_]:=Map[(a->#)&,f[a]]
j=Graph[Flatten[JJ  /@V]]

As the code suggested by @user6014 ignores the nested sets

$\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.