MATLAB: Change variable name in loop to store matrices

importimport datamake variable

Hello everyone!
I have a bunch of txt files with the same format that I want to store as numeric arrays (matrices). I want to store these matrices in variables with name of the respective txt file. So far I have used the Matlab GUI "Import" to generate a function that import one file. My problem is that I have hundreds of these txt files, therefore I want to make this import in a loop. However, I have problems creating the variable to store matrices inside the loop.
Here is short extract of the things I have been trying:
file = dir('myFolder\*.txt'); %my files
caseName = {file.name}; % caseName{1} for example yields >> results_case0001.txt
for i = 1:length(caseName)
[~ , filename, ~] = fileparts(caseName{i});
filename = importfile(caseName{i}); % importfile is the function generated with GUI Import tool
end
I thought that since
filename
changes for every iteration, that it could be used as a variable name, but it does not work. I would appreciate any help! Thanks in advance!
Best regards, Adriel

Best Answer

It is much simpler to just use indexing:
S = dir('myFolder\*.txt');
N = numel(S);
C = cell(1,N);
for kk = 1:N
C{kk} = importfile(S(kk).name);
end
This is just like the documentation shows:
What you are trying to do, magically naming variables after the filenames, is not recommended. It will make your code slow, complex, buggy, and hard to debug. Read this to know why: