Horizontally concatenate existing CSV columns

4 次查看(过去 30 天)
I have files in a directory, the directory location is saved to a variable called hardCodeFilePath
Within the directory hardCodeFilePath, there are five CSV files.
Each CSV is a single column of numerials WITH A STRING HEADER, which drives me mad as it creates a mixed data type.
Due to this mixed data type I can't just save them to numerical arrays and fiddle with them that way. (Blast!)
I saw a neat solution for joining multiple columns frOm mixed data type CSV files into a single mega-column but I am too much an idiot to make this join them horizontally in five columns instead of one vertical mega-column.
Here is that solution:
function ccsm()
sad = dir( 'x*.csv' ); % 1
% Is the order of the files important?
fid_out = fopen( 'concatenated_files.csv', 'w' ); % 2
for jj = 1 : length( sad ) % 3
fid_in = fopen( sad(jj).name, 'r' ); % 4
str = transpose( fread( fid_in, '*char' ) ); % 5
fclose( fid_in ); % 6
if not( jj == 1 ) % 7
ix1 = regexp( str, '[\r\n]++', 'once' ); % 8
str = str(ix1:end); % 9
end
ix2 = regexp( str, '[\r\n]++$', 'once' ); % 10
if not( isempty( ix2 ) ) % 11
str(ix2:end) = []; % 12
end
fwrite( fid_out, str, '*char' ); % 13
end
fclose('all'); % 14
end

采纳的回答

Star Strider
Star Strider 2017-7-15
If you have R2013b or later, and if your ‘.csv’ files all have the same number of rows, I would read each of them in separately with the readtable (link) function, and then horizontally concatenate the tables.
You can then save the concatenated table as a single table to another file using the writetable function.
  2 个评论
Constance Woodman
Constance Woodman 2017-7-15
Why, what a jolly good solution!!
Here is working script to implement that solution in case someone wants to try it!
colA = readtable('lowdataS1Roll1Hour.csv') colB = readtable('lowdataS1Yaw1Hour.csv')
fluttershy = horzcat(colA,colB)
writetable(fluttershy,'mergedCols.csv')

请先登录,再进行评论。

更多回答(1 个)

ANNE NDJALI
ANNE NDJALI 2019-3-9
编辑:ANNE NDJALI 2019-3-9
I have a similar problem, but my .csv files are not all the same number of rows. Is there a funciton that would work like the readtable + horzcat + writetable?
Thank you!

类别

Help CenterFile Exchange 中查找有关 File Operations 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by