combining different csv files from a folder into one matrix

조회 수: 7 (최근 30일)
Michel Nieuwoudt
Michel Nieuwoudt 2019년 5월 22일
댓글: Michel Nieuwoudt 2019년 5월 22일
Hello, I have 800 files with 1554rows and 2columns so (1554x2) , that I'd like to read from a folder and then combine them into a large matrix of 1554x801. The first column is common to each file, and so I'd like to set only the first column in the final matrix as the same column of all the files, and then the subsequent columns as the second column of each of the 800 files. I hope this makes sense.
Example:
A.csv=[1 2; 4 5] and B.csv=[1 8 ;4 7], C.csv=[1 6;4 10]
I'd like to combine these into
Combined=[1 2 8 6; 4 5 7 10]
Would anyone possibly have a code for this? I'm new to Matlab and have tried a number of codes that merge files. but they stack them horizontally so I get
[1 2;4 5;1 8;4 7;1 6;4 10].
Thank you!

채택된 답변

Stephen23
Stephen23 2019년 5월 22일
편집: Stephen23 2019년 5월 22일
"Is theremaybe a way to list the filenames in the same order, then add them afterwards as the top row to the table?"
You could use a table:
O = {'ReadVariableNames',false};
D = '.'; % path to the directory where the files are saved.
S = dir(fullfile(D,'*.csv'));
for k = 1:numel(S)
U = readtable(fullfile(D,S(k).name),O{:});
[~,N] = fileparts(S(k).name);
U.Properties.VariableNames = {'time',N};
if k==1
T = U;
else
T = join(T,U);
end
end
Giving (the test files are attached to this answer):
>> T
T =
time A B C
____ _ _ __
1 2 8 6
4 5 7 10
>> T.B
ans =
8
7
  댓글 수: 1
Michel Nieuwoudt
Michel Nieuwoudt 2019년 5월 22일
Hi Stephen,
This is exactly what I needed. Thank you so so much!
Best wishes,
Michel

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

KSSV
KSSV 2019년 5월 22일
csvfiles = dir('*.csv') ;
iwant = zeros(1554,801) ;
for i = 1:length(csvfiles)
data = csvread(csvfiles(i).name) ;
if i == 1
iwant(:,1:2) = data ;
else
iwant(:,i+1) = data(:,2) ;
end
end
  댓글 수: 8
KSSV
KSSV 2019년 5월 22일
It can be but...why unnecessary complexity? You should take it as a table.
Michel Nieuwoudt
Michel Nieuwoudt 2019년 5월 22일
I need to know the filename that each column represents. Is theremaybe a way to list the filenames in the same order, then add them afterwards as the top row to the table?

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Large Files and Big Data에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by