How to programatically make workspace variable name same as the .mat file name loaded into Matlab?
19 vues (au cours des 30 derniers jours)
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
Stephen23
le 1 Mai 2020
Modifié(e) : Stephen23
le 12 Juil 2023
"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
Stephen23
le 1 Mai 2020
A much better approach than awful dynamic variable names is to use simple, efficient indexing, e.g.:
D = 'path to the directory where the files are saved';
S = dir(fullfile(D,'*.mat'));
for k = 1:numel(S)
F = fullfile(D,S(k).name);
C = struct2cell(load(F));
S(k).data = C{1}; % assumes exactly ONE variable per file
end
All of the data will be stored in the structure S:
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
Voir également
Catégories
En savoir plus sur Standard File Formats dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!