store workspace file in variables using a for loop

4 visualizaciones (últimos 30 días)
Robin Strak
Robin Strak el 16 de Mzo. de 2020
Comentada: Robin Strak el 17 de Mzo. de 2020
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.

Respuesta aceptada

Stephen23
Stephen23 el 17 de Mzo. de 2020
Editada: Stephen23 el 17 de Mzo. de 2020
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 comentario
Robin Strak
Robin Strak el 17 de Mzo. de 2020
thanks a lot, I will definitely have a look at your links!

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Creating and Concatenating Matrices en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by