Search code examples
matlabopencvmat-file

How to access the "Value" in a .mat file without knowing the name?


I need to load in a .mat file and extract the data. The .mat file will always store one variable with a "Name" and a "Value":

'name' <1024x1280x20 uint8> (for example)

To access the data, I currently have to know the variable name, so I do something like:

matfile = 'somematfile.mat';
load(matfile);
if exist('name','var')
    data=name;
end

I'm wondering how to do this without knowing what the variable name is in the MAT File.

Cheers, Sean


Solution

  • Use M=load(matfile);, then you get a struct with all variables in the matfile. Use f=fieldnames(M) to get a list of all variables in the struct and M.(f{1}) to access the first variable (assuming you have only 1)