Import N excel files in N matrix, with name in function of a variable
75 次查看(过去 30 天)
显示 更早的评论
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 个评论
Stephen23
2024-10-28,11:06
编辑:Stephen23
2024-10-28,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:
采纳的回答
Hitesh
2024-10-28,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
更多回答(1 个)
埃博拉酱
2024-10-28,13:25
编辑:埃博拉酱
2024-10-28,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 个评论
Stephen23
2024-10-28,13:45
编辑:Stephen23
2024-10-28,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".
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!