How to programatically make workspace variable name same as the .mat file name loaded into Matlab?
Afficher commentaires plus anciens
I have a number of .mat files in a folder called m2.mat, m3.mat, m4.mat and so on all the way to m400.mat. When each .mat file is loaded into Matlab, the associated workspace variable has a different name. For example, m2.mat has a workspace name as data_run_2, and m3.mat has a workspace name as data_run_3. I would like all worspace variables to have the same name as the .mat file name, thus m2.mat would have the workspace name m2. Is there a way to programatically perform this operation for all of the 400 files?
Thanks so much for the assistance!
1 commentaire
"I would like all worspace variables to have the same name as the .mat file name, thus m2.mat would have the workspace name m2"
Ugh, no, that would be entirely the wrong approach.
"is there a way to programatically perform this operation for all of the 400 files?"
Yes, there are several ways... that are all best avoided. Read this to know why:
If you want to write neat, simple, efficient code (and waste less of your time writing and debugging it) then every .mat file should contain variables with exactly the same names. That is the best, simplest, most robust data design. If you unfortunately already have been given MAT files containing different variable names, then import them MAT files into a structure and access its fields:
S = load(..)
Réponse acceptée
Plus de réponses (1)
Fangjun Jiang
le 1 Mai 2020
Modifié(e) : Fangjun Jiang
le 1 Mai 2020
It is possible but may not need to. Using the following approach can enable you always use Var.(MyVar) to refer your variable. Otherwise, you just need to load the .mat file, copy the varialbe and save a new .mat file, for 400 times.
Var=load('m2.mat');
VarNames=fieldnames(Var);
MyVar=VarNames{1}; % assume there is always just one variable in the .mat file
TheData=Var.(MyVar) % you don't even need to know the variable name in the .mat file
clear Var VarNames MyVar
1 commentaire
Brent Weyers
le 1 Mai 2020
Catégories
En savoir plus sur Workspace Variables and MAT Files dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!