How can I import .csv files and then save each as a new matrix using for loop?

1 view (last 30 days)
I want to assign variable names to matrices created after importing .csv files from the current folder.
My code:
csv_files = dir('*.csv');
num_csv = length(csv_files);
for k = 1:num_csv
T{k} = importdata(csv_files(k).name);
T1 = T{k};
end
T is a {1x5} cell array each containing the data matrices that I want separated and named. The output for T1 is only the last file that was run through. I can manually assign the variables to get the desired result like so:
T1 = T{1};
T2 = T{2};
T3 = T{3};
T4 = T{4};
T5 = T{5};
However, I will have more data files for my future projects and would like this to be done in the same for loop. Any help would be greatly appreciated!
Thank you
  2 Comments
Stephen23
Stephen23 on 26 May 2017
Edited: Stephen23 on 26 May 2017
"Any help would be greatly appreciated!"
The best help that you will receive is the advice "DO NOT DO THIS". Yes, beginners sometimes believe that they should create or access variables names dynamically, and that this will solve all of their problems. It won't. It will make your code slow, complicated, buggy, hard to debug, hard to read,... and is a bad habit to learn.
"I will have more data files for my future projects"
So now is a good time to learn good programming practices then. It might not seem like it when you begin, but actually learning good code practices will save you an enormous amount of time later, whereas if you start using dynamic variable names now, then nothing will be able to save you from slow, buggy, hard-to-debug code later.
You might like to read the MATLAB documentation, which clearly advises against creating and accessing variable names like that: "A frequent use of the eval function is to create sets of variables such as A1, A2, ..., An, but this approach does not use the array processing power of MATLAB and is not recommended. The preferred method is to store related data in a single array."
You can also see what other experienced MATLAB users have to say:
You will find better alternatives listed, but most of them can be summarized in one word: indexing. Indexing is simpler, faster, neater, much more efficient, easier to debug, easier to read, ...
Jessica Shull
Jessica Shull on 26 May 2017
Thanks for you feedback, Stephen. I now understand why using dynamic variables is not a good approach and I will try indexing.

Sign in to comment.

Answers (1)

Walter Roberson
Walter Roberson on 25 May 2017

Community Treasure Hunt

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

Start Hunting!