简体   繁体   English

如何加载多个CSV文件并存储在数组中?

[英]How to load multiple CSV files and store in an array?

My CSV files are spectra data of the type A1a(1:853,1:853) . 我的CSV文件是A1a(1:853,1:853)类型的光谱数据。 Column 1 contains wavelength information, Column 2 contains intensity information. 第1列包含波长信息,第2列包含强度信息。

I have multiple CSV files in a folder, A1a, A1b, A1c.....A1k.csv and I would like to store these files in an array of type A(10,1:853,1:853) using csvread and a for loop. 我在一个文件夹A1a, A1b, A1c.....A1k.csv有多个CSV文件,我想使用csvread和这些文件将它们存储在A(10,1:853,1:853)类型的数组中一个for循环。

How can I do this? 我怎样才能做到这一点?

You can use dir with dlmread (or csvread , a wrapper for dlmread ) to read in your data. 您可以使用dirdlmread (或csvread ,对于包装dlmread )在数据读取。 This example assumes the size of each data file is uniform and you know the exact structure of your data: 本示例假定每个数据文件的大小是一致的,并且您知道数据的确切结构:

% Generate some sample data
fID = fopen('A1a.csv', 'w');
fprintf(fID, '%u,%u,%u\n', repmat(1:5, 3, 1));
fclose(fID);

fID = fopen('A1b.csv', 'w');
fprintf(fID, '%u,%u,%u\n', repmat(6:10, 3, 1));
fclose(fID);

fID = fopen('A1c.csv', 'w');
fprintf(fID, '%u,%u,%u\n', repmat(11:15, 3, 1));
fclose(fID);

% Preallocate array if you know for sure how your data is structured
nfiles = 3;
nrows = 5;
ncols = 3;
mydata = zeros(nrows, ncols, nfiles);

% Read in your data
nheaderlines = 0;
nskipcolumns = 0;
filestoread = dir('A1*.csv');

for ii = 1:length(filestoread)
    mydata(:, :, ii) = dlmread(filestoread(ii).name, ',', nheaderlines, nskipcolumns);
end

This gives us mydata as a [5x3x3] array, where mydata(:,:,1) is A1a.csv , mydata(:,:,2) is A1b.csv , and mydata(:,:,3) is A1c.csv . 这使mydata成为[5x3x3]数组,其中mydata(:,:,1)A1a.csvmydata(:,:,2)A1b.csvmydata(:,:,3)A1c.csv

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM