Import N excel files in N matrix, with name in function of a variable
75 views (last 30 days)
Show older comments
Andrea
on 28 Oct 2024 at 10:57
Commented: Andrea
on 28 Oct 2024 at 13:51
I have a large number of excel file with the name like: NAME.000i000.csv where i is a variable, from 0 to N.
to import a single file I use this line of code and perfectly work
DATA1 = readtable("DIR\NAME.0001000.csv", opts);
How can I import all the N file and create N matrix with the name DATAi?
I have tried something similar to:
for i=1:N
eval(['DATA' num2str(i) '= i'])=readtable(""DIR\NAME.000%s000.csv",i, opts);
end
but it didn't work.
Thank you for your help
2 Comments
Stephen23
on 28 Oct 2024 at 11:06
Edited: Stephen23
on 28 Oct 2024 at 12:43
Rather than awkwardly forcing pseudo-indices into variable names (and making your data harder to work with) the much better approach is to use actual indexing into one array, for example:
C = cell(1,N);
for k = 1:N
fnm = ..
C{k} = readtable(fnm,opts);
end
Using indexing is more efficient, more robust, easier to work with, less buggy, and easier to debug.
Using indexing is exactly what the MATLAB documentation recommends:
Accepted Answer
Hitesh
on 28 Oct 2024 at 11:41
Hi Andrea,
You need to use structure within the loop to dynamically create variables for each corresponding CSV file when importing multiple CSV files in MATLAB. However, using "eval" for creating variable names dynamically is generally discouraged due to potential issues with code readability and debugging.
For more information on " Why Variables Should Not Be Named Dynamically (eval)", refer to the following link:
Refer the following code for achieving same using structure:
N = 10; % Replace with your actual number of files
DATA = struct(); % Initialize an empty structure
for i = 1:N
fileName = sprintf('DIR\NAME.000%d000.csv', i);
DATA.(sprintf('DATA%d', i)) = readtable(fileName);
end
More Answers (1)
埃博拉酱
on 28 Oct 2024 at 13:25
Edited: 埃博拉酱
on 28 Oct 2024 at 13:26
DATA=arrayfun(@(Filename)readtable(Filename,opts),compose("DIR\NAME.000%u000.csv",1:N),UniformOutput=false);
%If you insist on creating a series of workspace variables called DATAi despite the dissuasion of others:
arrayfun(@eval,compose("DATA%u=Data{%u};",1:N));
1 Comment
Stephen23
on 28 Oct 2024 at 13:45
Edited: Stephen23
on 28 Oct 2024 at 13:49
"...despite the dissuasion of others"
and also despite the dissuasion of the MATLAB documentation, which states "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".
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!