Get unknown variable from mat-file
Show older comments
I am frequently facing a similar problem: I need to load a variable from a mat-file, and the variable name is unknown. For example, I know the variable contains a signal to be processed but the name may be whatever.
I am aware of this answer https://www.mathworks.com/matlabcentral/answers/380840-select-an-unknown-variable-from-mat-file (thanks Jan!), and applying that method I can do it like this:
matObj = matfile(fileName);
varName = whos(matObj);
myVar = matObj.(varName(1).name);
However, this is still quite clumsy taking into account that I know for sure there is only one variable in the file, and I just wonder isn't there any faster method that does not involve using 'whos'? I do not need to get a list of variables. I just want the only one variable that exists there.
Yeah, I know I can do it also like this:
tmp = load(fileName);
str = fieldnames(tmp);
myVar = tmp.(str{1});
but this is even clumsier. So, is there any method that does not need getting a list of names and/or using temporary variable?
Accepted Answer
More Answers (0)
Categories
Find more on Workspace Variables and MAT Files 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!