Read MATLAB graph objects into Python
13 views (last 30 days)
Show older comments
MATLAB has a representation of a directed/undirected graph. I would like to deserialize a graph serialized via MATLAB's save function into Python. I know about scipy.io.loadmat and h5py's File, but neither seems to produce a representation in Python that actually holds intelligible vertex/edge data.
How do I do this? I'm concerned with this and the inverse operation, i.e writing an object from Python to a format MATLAB load can read. Is there a bytewise data description of what a serialized MATLAB objects and a Graph looks like somewhere?
For example, in MATLAB I could:
s = [1 1 2 2 3];
t = [2 4 3 4 4];
G = digraph(s,t);
G.Edges.Rand = rand(size(G.Edges)); % Add an edge attribute
G.Nodes.Val = rand(size(G.Nodes)); % Add an a node attribute
save('loadmat.mat', 'G'); % Readable by scipy.io.loadmat
save('h5py.mat', 'G', '-v7.3'); % Readable by h5py.File
then, in Python I could read these
from scipy.io import loadmat
G0 = loadmat('loadmat.mat')
from h5py import File
G1 = File('h5py.mat')
Thanks
0 Comments
Answers (1)
Christine Tobler
on 18 Dec 2015
I don't know much about python loadmat and h5py files, but I don't think loading the MATLAB object graph would realistically work. The classes graph/digraph are described in MATLAB code which will not be available in python, so even if you could load the internal data, this would not give you access to any of the graph object's methods and properties in python.
I would suggest that instead, you could save the edge list or the adjacency matrix of the graph in a .mat file:
[s, t] = findedge(g); M = adjacency(g);
Whichever python package you are using to represent graphs is likely to be able to construct a graph from one or both of these.
2 Comments
Christine Tobler
on 18 Dec 2015
Unfortunately, I don't have a bytewise description, as I don't know what mat-serialization does internally. To just get all the graph attributes into python, you might try doing
edgeStruct = table2struct(g.Edges);
nodeStruct = table2struct(g.Nodes);
These two structs should contain all information in the graph object, and should be parseable as you mentioned.
See Also
Categories
Find more on Call Python from MATLAB in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!