Extracting a row of data from multiple files and loop into a calculation.

1 次查看(过去 30 天)
I have 6 separate files each with 3 columns of data with an unknown number of rows. I am trying to use the first row of each file as a line in a new matrix i.e end up with a 6*3 matrix. I want to repeat this for every row until it ends.
Does this make sense? Does anyone know how to do this?

回答(1 个)

Guillaume
Guillaume 2018-2-27
Presumably all the files have the same number of rows. Otherwise, you need to specify what to do with the extra rows in some of the files.
filenames = compose('file%d.csv', 1:6); %name of files to open. Generated however you want. Possibly with dir
filedata = cell(1, numel(filenames)); %cell array to receive arrays of unknown size
%read the content of all the files:
for fileidx = 1:numel(filenames)
filedata{fileidx} = csvread(fullfile('C:\somewhere', filenames{fileidx})); %read the file. May need something other than csvread depending on the file
end
%concatenate and permute into desired shape:
filedata = cat(3, filedata{:}); %concatenate into 3D array. Will error if the files are not all the same size
filedata = permute(filedata, [3 2 1]);
The resulting filedata is a numfiles x numcolumns x numrows matrix, so in your case 6 x 3 x unknownnumber. You could split this into a cell array of 6x3 matrices if you really desire:
filedata = squeeze(num2cell(filedata, [1 2])); %cell array of numfiles x numcolumns matrices

类别

Help CenterFile Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息

标签

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by