필터 지우기
필터 지우기

How to programatically make workspace variable name same as the .mat file name loaded into Matlab?

조회 수: 18 (최근 30일)
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
Stephen23
Stephen23 2020년 5월 1일
편집: Stephen23 2023년 7월 12일
"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(..)

댓글을 달려면 로그인하십시오.

채택된 답변

Stephen23
Stephen23 2020년 5월 1일
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:

추가 답변 (1개)

Fangjun Jiang
Fangjun Jiang 2020년 5월 1일
편집: Fangjun Jiang 2020년 5월 1일
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

카테고리

Help CenterFile Exchange에서 Standard File Formats에 대해 자세히 알아보기

제품


릴리스

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by