Azzera filtri
Azzera filtri

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

4 visualizzazioni (ultimi 30 giorni)
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');

Risposta accettata

Ameer Hamza
Ameer Hamza il 15 Giu 2020
Modificato: Ameer Hamza il 15 Giu 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');

Più risposte (0)

Categorie

Scopri di più su Matrices and Arrays in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by