Clear Filters
Clear Filters

Concatenate two columns of a csv file using horzcat with same variable name

4 views (last 30 days)
I have few csv files, each has 3 columns with first two columns same in all. I want to merge all of them into a single csv file with first two common columns and continued with 3rd column of each individual files. Error associated is the same variable name for the 3rd column in all csv files. I'm attaching my code. Thanks in advance!
clc
clear all
close all
files = dir('*.csv');
A = readtable(files(1).name);
numfiles = length(files);
for k=2:numfiles
filename = files(k).name;
T = readtable(filename,"ReadVariableNames",true,"PreserveVariableNames",true);
A = horzcat(A, T(:,3));
end
writetable(A,'mergedCols.csv');

Accepted Answer

Ameer Hamza
Ameer Hamza on 15 Jun 2020
Edited: Ameer Hamza on 15 Jun 2020
In MATLAB, two columns of a table cannot have the same variable name. Also, it might not make sense to have identical column names in a CSV file. However, you can do this using cell arrays instead of tables. Something like this
files = dir('*.csv');
A = readtable(files(1).name);
A = [A.Properties.VariableNames; table2cell(A)];
numfiles = length(files);
for k=2:numfiles
filename = files(k).name;
T = readtable(filename,"ReadVariableNames",true,"PreserveVariableNames",true);
A = horzcat(A, [T.Properties.VariableNames(3); num2cell(T{:,3})]);
end
writecell(A, 'mergedCols.csv');

More Answers (0)

Categories

Find more on Matrices and Arrays 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!