Import N excel files in N matrix, with name in function of a variable
75 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
Andrea
il 28 Ott 2024 alle 10:57
Commentato: Andrea
il 28 Ott 2024 alle 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 Commenti
Stephen23
il 28 Ott 2024 alle 11:06
Modificato: Stephen23
il 28 Ott 2024 alle 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:
Risposta accettata
Hitesh
il 28 Ott 2024 alle 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
Più risposte (1)
埃博拉酱
il 28 Ott 2024 alle 13:25
Modificato: 埃博拉酱
il 28 Ott 2024 alle 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 Commento
Stephen23
il 28 Ott 2024 alle 13:45
Modificato: Stephen23
il 28 Ott 2024 alle 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".
Vedere anche
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!