store workspace file in variables using a for loop

조회 수: 1 (최근 30일)
Robin Strak
Robin Strak 2020년 3월 16일
댓글: Robin Strak 2020년 3월 17일
Hi,
I´ve got lots of .txt files in my folder and loaded them into the workspace. All of them contain a 1001x7 matrix, e.g.
9.7 9.7 9.7 144.5 79.1 142.6 84
9.7 9.7 9.7 123.6 88.1 156.7 80.3
9.7 9.7 9.7 125.3 90.7 149.1 78.1
9.7 9.7 9.7 133.6 82.6 105.6 76.8
9.7 9.7 9.7 115 85.1 90.1 81.5
...
As they are named as aaa_bbb_ccc I would like to filter them and store them into a variable.
For example I want to search my workspace for ending "_ccc" and store all of them into their own variable.
By using the who-function I was able to output the names of the matrix into the command window, but not save them as a variable.
I would be very happy to get some help as I couldn´t find any corresponding question here.

채택된 답변

Stephen23
Stephen23 2020년 3월 17일
편집: Stephen23 2020년 3월 17일
Your approach is entirely the wrong way around. Putting meta-data (e.g. pseudo-indices, subject IDs, parameter values, etc.) into variable names is a sign that you are doing something wrong.
Accessing variable names dynamically is one way that beginners force themselves into writing slow, complex, obfuscated, buggy code that is hard to debug. Read this to know why:
You would be much better off loading the data into one array (e.g. a cell array or a structure) and then using a simple loop. For example:
P = 'absolute/relative path to where the files are saved';
S = dir(fullfile(P,'*.txt'));
for k = 1:numel(S)
S(k).data = dlmread(fullfile(P,S(k).name));
end
Now all of the file data will be contained in the non-scalar structure S. You can trivially loop over the elements of S and process each file's data. Or you can get the filenames and filter for whichever ones you want, which makes it easy to combine the matrices exactly as you asked in your question, e.g.:
F = {S.name};
[~,F] = cellfun(@fileparts,F,'uni',0); % optional
X = ~cellfun(@isempty,regexp(F,'ccc$')); % or use ENDSWITH
ccc = cat(1,S(X).data); % if the matrices have compatible sizes
You need to understand how to use comma-separated lists:
  댓글 수: 1
Robin Strak
Robin Strak 2020년 3월 17일
thanks a lot, I will definitely have a look at your links!

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by