How to read name of a recently imported struct

20 ビュー (過去 30 日間)
Maximilian Prechtl
Maximilian Prechtl 2018 年 11 月 5 日
編集済み: Stephen23 2018 年 11 月 5 日
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

回答 (2 件)

Walter Roberson
Walter Roberson 2018 年 11 月 5 日
datastruct = load('Example.mat');
storedvars = fieldnames(datastruct) ;
FirstVarName = storedvars{1};
FirstVarContent = datastruct.(FirstVarName);

Stephen23
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.

カテゴリ

Help Center および File ExchangeWorkspace Variables and MAT Files についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by