Horizontally concatenate existing CSV columns
4 views (last 30 days)
Show older comments
Constance Woodman
on 15 Jul 2017
Edited: ANNE NDJALI
on 9 Mar 2019
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
0 Comments
Accepted Answer
Star Strider
on 15 Jul 2017
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 Comments
More Answers (1)
ANNE NDJALI
on 9 Mar 2019
Edited: ANNE NDJALI
on 9 Mar 2019
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!
0 Comments
See Also
Categories
Find more on File Operations in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!