Importing multiple excel sheet's data into individual variables
3 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Alexander Seal
el 8 de Nov. de 2016
Respondida: Hannes Daepp
el 14 de Nov. de 2016
Very similar to this question, I want to import multiple columns from multiple excel sheets and create a column vector with a name based on the input file. What I've managed to do so far is import all of one variable from all sheets into one array, but I want them separately.
source_dir ='E:\xxxx'
source_files = dir(fullfile(source_dir,'*.csv'));
for k=1:length(source_files)
d{k} = xlsread(fullfile(source_dir,source_files(k).name), 'A:A'); %distance upstream
e{k} = xlsread(fullfile(source_dir,source_files(k).name), 'D:D'); %elevation upstream
x{k} = xlsread(fullfile(source_dir,source_files(k).name), 'B:B'); %x co-ord
y{k} = xlsread(fullfile(source_dir,source_files(k).name), 'C:C'); %y co-ord
a{k} = xlsread(fullfile(source_dir,source_files(k).name), 'E:E'); %upstream area
s{k} = xlsread(fullfile(source_dir,source_files(k).name), 'F:F'); %local slope
end
I'd want outputs of d111, e111, x111 etc, where 111 is the file name.
0 comentarios
Respuesta aceptada
Hannes Daepp
el 14 de Nov. de 2016
As I understand, you would like to have separate variables for each entry, rather than storing them in the cell arrays as you have done above, and you would like those variables to be automatically generated based on the name of the input file.
You can do this using the "eval" command, though it is generally discouraged because it's inefficient and can be difficult to debug. That issue is elaborated upon in this past Answers post: https://www.mathworks.com/matlabcentral/answers/143-how-do-i-make-a-series-of-variables-a1-a2-a3-a10
For example, you could instead generate fields of a structure and populate that:
>> varname = matlab.lang.makeValidName(source_files(k).name(1:end-4));
>> myData.(varname) = xlsread(fullfile(source_dir,source_files(k).name), 'A:A');
The first line is to ensure that you define allowable variable names: http://www.mathworks.com/help/matlab/ref/matlab.lang.makevalidname.html
If you are set on automatic variable generation, you could do that using "eval":
>> varname = matlab.lang.makeValidName(source_files(k).name(1:end-4));
>> eval([varname '= xlsread(fullfile(cd, source_dir,source_files(k).name),'...
char(39) 'A:A' char(39) ');']);
However, as noted above, I would encourage you to explore other options. You may find the following documentation to provide some useful suggestions: http://www.mathworks.com/help/matlab/matlab_prog/string-evaluation.html
0 comentarios
Más respuestas (0)
Ver también
Categorías
Más información sobre Spreadsheets en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!