Effacer les filtres
Effacer les filtres

Horizontally concatenate existing CSV columns

4 vues (au cours des 30 derniers jours)
Constance Woodman
Constance Woodman le 15 Juil 2017
Modifié(e) : ANNE NDJALI le 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

Réponse acceptée

Star Strider
Star Strider le 15 Juil 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 commentaires
Constance Woodman
Constance Woodman le 15 Juil 2017
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')
Star Strider
Star Strider le 15 Juil 2017
Thank you!

Connectez-vous pour commenter.

Plus de réponses (1)

ANNE NDJALI
ANNE NDJALI le 9 Mar 2019
Modifié(e) : ANNE NDJALI le 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!

Catégories

En savoir plus sur File Operations dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by