Load and access a MATLAB-generated graph network in Python
35 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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 Kommentare
Antworten (1)
Gayatri Rathod
am 27 Apr. 2023
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:
- 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!
0 Kommentare
Siehe auch
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!