How to load in variable if it is present in a matfile?
Ältere Kommentare anzeigen
I am having trouble with "conditional" loading of a variable from a matfile, depending on whether the matfile contains the variable. Here is what I am trying to do:
- Go through many different (large) matfiles, some of which contain mountain height in a variable called topo, and some of which contain mountain height in variable called elevation.
- If the matfile contains the variable topo, load that into a workspace variable called mountainHeight. If the matfile contains the variable elevation, load that into a workspace variable called mountainHeight. If neither variable is contained in matfile, do nothing.
- Avoid crashing the load command by trying to load variables which are not in the matfile.
Here is what I have tried (R2015a), but I'd bet there is a better/shorter way.
filename = 'topography.mat'; % A matfile that comes with matlab
m = matfile(filename); % Make a matfile object
FileInfo = whos(m); % Structure containing information about matfile including variables it contains
for iVar = 1:length(FileInfo)
if strcmp(FileInfo(iVar).name, 'topo') % Check if topo is a variable in topography.mat
mountainHeight = m.topo; % Load topo
elseif strcmp(FileInfo(iVar).name, 'elevation') % Check if elevation is a variable in topography.mat
mountainHeight = m.elevation; % Load elevation
end
end
Akzeptierte Antwort
Weitere Antworten (2)
Sean de Wolski
am 21 Jul. 2015
Bearbeitet: Sean de Wolski
am 23 Jul. 2015
1 Stimme
Use this to determine what's in the MAT file, then use the MAT File class to load that variable in.
1 Kommentar
K E
am 24 Jul. 2015
Or you can turn off this warning and just test if the output struct is empty (at least on 2015b-pre, I can't test on earlier versions now).
Kategorien
Mehr zu Whos finden Sie in Hilfe-Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!