Get unknown variable from mat-file

48 views (last 30 days)
Petri M
Petri M on 21 Jan 2021
Edited: Stephen23 on 21 Jan 2021
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

Stephen23
Stephen23 on 21 Jan 2021
Edited: Stephen23 on 21 Jan 2021
Given only one variable saved in the mat file:
tmpC = struct2cell(load(filename));
myVar = tmpC{1};
Do not worry about the temporary variable, it does NOT copy the array data, just creates a cell array header (about 100 bytes or so) which links to the actual array location. Your imported data array is unaffected:
  2 Comments
Stephen23
Stephen23 on 21 Jan 2021
Edited: Stephen23 on 21 Jan 2021
"but this involves temporary variable, which is not good if I have large variables"
Which is why I wrote in my answer that it does NOT create a copy of the data array. The size of the actual data array is totally irrelevant, because it is NOT copied or moved. All that happens is that the reference (in the structure field) is copied to a cell array header (around 100 bytes per cell). The data array is most likely not copied, moved, or otherwise affected by this. Please read the link I gave to learn how MATLAB actually works (there are also plenty of discussions on this topic within this forum).
If the data arrays cannot fit into memory (or be processed once in memory), then you could consider using tall arrays instead:
Petri M
Petri M on 21 Jan 2021
Edited: Petri M on 21 Jan 2021
Thank you so much! Obviously you noticed my previous comment that I now deleted :) I tested this and indeed the copy does not waste any memory.

Sign in to comment.

More Answers (0)

Categories

Find more on Characters and Strings in Help Center and File Exchange

Products


Release

R2020b

Community Treasure Hunt

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

Start Hunting!