Filter löschen
Filter löschen

Horizontally concatenate existing CSV columns

4 Ansichten (letzte 30 Tage)
Constance Woodman
Constance Woodman am 15 Jul. 2017
Bearbeitet: ANNE NDJALI am 9 Mär. 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

Akzeptierte Antwort

Star Strider
Star Strider am 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 Kommentare
Constance Woodman
Constance Woodman am 15 Jul. 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 am 15 Jul. 2017
Thank you!

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (1)

ANNE NDJALI
ANNE NDJALI am 9 Mär. 2019
Bearbeitet: ANNE NDJALI am 9 Mär. 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!

Kategorien

Mehr zu File Operations finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by