Load and access a MATLAB-generated graph network in Python

33 次查看(过去 30 天)
I've saved a digraph using
io_utils.save_mat(fullfile(TASK_DIR, 'Graph.mat'), Graph);
Now I want to access the graph nodes and edges by loading the .mat file in Python.
I tried,
r = sio.loadmat(TASK_DIR / "Graph.mat", struct_as_record=False, squeeze_me=True)
print(getattr(r, 'digraph'))
returns the following error
AttributeError: 'types.SimpleNamespace' object has no attribute 'digraph'
{'__header__': b'MATLAB 5.0 MAT-file, Platform: PCWIN64, Created on: Thu Mar 2 13:42:35 2023', '__version__': '1.0', '__globals__': [], 'None': MatlabOpaque([(b'variable', b'MCOS', b'digraph', array([3707764736, 2, 1, 1, 1,
3], dtype=uint32)) ],
dtype=[('s0', 'O'), ('s1', 'O'), ('s2', 'O'), ('arr', 'O')]), '__function_workspace__': array([[ 0, 1, 73, ..., 0, 0, 0]], dtype=uint8)}
dict_keys(['__header__', '__version__', '__globals__', 'None', '__function_workspace__'])
I am not sure how to access the nodes and edges.
Suggestions will be really helpful.
  2 个评论
Raghav
Raghav 2023-3-7
编辑:Raghav 2023-3-9
Hi,
Can you provide the 'Graph.mat' file, so that I can check the issue at my end.
Thanks,
Raghav Bansal

请先登录,再进行评论。

回答(1 个)

Gayatri Rathod
Gayatri Rathod 2023-4-27
Hi Deepa,
  • Based on the output you provided, it looks like the digraph object is stored as an instance of a MatlabOpaque class in the 'None' field of the loaded dictionary. The error message you received indicates that the loaded object is of type types.SimpleNamespace, which is not a digraph object.
  • It seems that the loadmat function is returning the object as a dictionary with keys corresponding to the variables in the .mat file. In this case, the variable name is 'None'.
Here's an example of how you can extract the digraph object from the loaded dictionary and access its nodes and edges:
  1. Load the .mat file and get the 'None' variable.
import scipy.io as sio
mat_contents = sio.loadmat("Graph.mat")
mat_var = mat_contents['None']
2. Access the 'digraph' object with proper indexing and save it to graph_obj variable.
3. Access the nodes and edges of graph_obj
nodes = graph_obj.nodes;
edges = graph_obj.edges;
4. Print the nodes and edges.
print(nodes)
print(edges)
The graph_obj variable should now contain the digraph object and you can access its nodes and edges using the nodes and edges properties.
You can read more about the loadmat and MatlabOpaque from the following documentations: loadmat doc, MatlabOpaque doc.
Hope it helps!

类别

Help CenterFile Exchange 中查找有关 Networks 的更多信息

产品


版本

R2021a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by