How to read name of a recently imported struct
조회 수: 20 (최근 30일)
이전 댓글 표시
Hello all,
my Matlab version is R2017a.
So here comes by problem, I hope the information is clear and you can help me:
I imported data from a .m file as a struct. Let's say the files name is "Example.mat"
load('Example.mat')
Now what I get is a new struct in my workspace which's name differs from the filename. Let's say the structs name is "NotTheFileName" (1x1 struct).
So here comes my question:
I want to give matlab the filename (in our case "Example.mat"), than load it into the workspace, get the name of the struct (in our case "NotTheFileName") and make it work on with this.
What I currently do is loading the file by giving the name, than reading the struct name by myself and writing it manually into my code - a really bad solution.
Anyone can help me with that?
Best Regards Max
댓글 수: 0
답변 (2개)
Walter Roberson
2018년 11월 5일
datastruct = load('Example.mat');
storedvars = fieldnames(datastruct) ;
FirstVarName = storedvars{1};
FirstVarContent = datastruct.(FirstVarName);
댓글 수: 0
Stephen23
2018년 11월 5일
편집: Stephen23
2018년 11월 5일
"What I currently do is loading the file by giving the name, than reading the struct name by myself and writing it manually into my code - a really bad solution."
Yep.
"Anyone can help me with that?"
Simple: always load any .mat file data into an output variable (which itself is a scalar structure). If your .mat file only contains one variable, then you can get your array in just two lines:
C = struct2cell(load('Example.mat'));
A = C{1} % the array that you want to use.
If the .mat file contains multiple variables, then you will need to use load's regular expression option to return just one, or select the required array using the output structure's fieldnames.
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Workspace Variables and MAT Files에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!