Get unknown variable from mat-file

52 visualizaciones (últimos 30 días)
Petri M
Petri M el 21 de En. de 2021
Editada: Stephen23 el 21 de En. de 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?

Respuesta aceptada

Stephen23
Stephen23 el 21 de En. de 2021
Editada: Stephen23 el 21 de En. de 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 comentarios
Stephen23
Stephen23 el 21 de En. de 2021
Editada: Stephen23 el 21 de En. de 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 el 21 de En. de 2021
Editada: Petri M el 21 de En. de 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.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Characters and Strings en Help Center y File Exchange.

Etiquetas

Productos


Versión

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by