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

조회 수: 2 (최근 30일)
C Smyth
C Smyth 2018년 2월 27일
답변: Guillaume 2018년 2월 27일
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에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by