Dynamic Variables in Loop
조회 수: 3 (최근 30일)
이전 댓글 표시
I need to import a lot of data from different files by specific criteria. Therefore i wrote an ImportLoop that reads all the data files.
Till now i have a problem generating different VariableNames in the Loop. The Variables shouldn't be named A1, A2,... like in the
eval( [ ['a' int2str(k) ] '=.....)
function. The VaribaleName MUST BE the name of the file i import in the loop, therefore i need the variable name to change dynamically inside:
path = 'C:\Users\(...)\*.txt';
files = dir(path);
names = {files.name}; %Array with all the relevant FileNames
rootdir = "C:\Users\(...)\";
for k=1:numel(names)
(...)
[regexprep(extractBetween((names{k}),"A","."), '-', '')] = readtable(fullfile(rootdir, names{k}), opts);
end
I have read the whole despription why i shouldn't use dynamic variables but i havn't found any other solution that works cause the file names get imported randomly and therefore i need the FileName as VariableName to refer to it later in the code specifically.
So please don't just post me the Link, i have seen it 200 times so far.
Ty so much in advance.
댓글 수: 1
Stephen23
2020년 11월 9일
편집: Stephen23
2020년 11월 9일
Context of this question:
"I have read the whole despription why i shouldn't use dynamic variables but i havn't found any other solution that works..."
Indexing works.
"... cause the file names get imported randomly..."
Have you tried using the answer you were given to your earlier question?:
"The VaribaleName MUST BE the name of the file i import in the loop, therefore i need the variable name to change dynamically inside:"
I very much doubt that it "MUST BE" named the same, it is much easier to store meta-data (such as filenames) as data in their own right, and use indexing to store that data in a loop. Using indexing is also what that MATLAB documentation recommends:
채택된 답변
Ameer Hamza
2020년 11월 9일
편집: Ameer Hamza
2020년 11월 9일
Now that you are already aware of the problem with using eval to create variable names dynamically, a better approach is to use cell arrays; however, if you want to link filenames to the data, then use a struct. For example,
path = 'C:\Users\(...)\*.txt';
files = dir(path);
data = struct();
for k=1:numel(files)
opt = ..
filename = fullfile(files(i).folder, files(i).name);
variable_name = regexprep(extractBetween((names{k}),"A","."), '-', '');
data.(variable_name) = readtable(filename, opts);
end
data is a struct that contains the same field name as the filenames.
Another solution is to use the file struct to save the data directly.
path = 'C:\Users\(...)\*.txt';
files = dir(path);
for k=1:numel(files)
opt = ..
filename = fullfile(files(i).folder, files(k).name);
files(k).data = readtable(filename, opts);
end
댓글 수: 2
추가 답변 (0개)
참고 항목
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!