How can I split a .csv file after a change of value (string) in a column?

조회 수: 9 (최근 30일)
Hi everybody,
Sorry for (maybe) the easy question, but I don't have any experience on splitting .csv file and the online search didn't go well. I have a .csv file that appear like this
I want to create different .csv file, with the same header, when there's a change in column 'ParticipantName'. How can I do this in MatLab?
Thank you for your answers!

답변 (1개)

Vishwanath Bailore Acharya
Vishwanath Bailore Acharya 2018년 2월 13일
편집: Vishwanath Bailore Acharya 2018년 2월 14일
Hello Riccardo,
I have reproduced the issue by creating a sample CSV file. I have split the CSV file into multiple files whenever there is a change in a column ‘Pname’.
Refer to the code below,
table = readtable('demo.csv');
names = table.Pname;
[r,c] = size(table);
k=1;
name=names{1}
start=1;
%Loop to detect a change value in the column Pname and splitting the file
%into a new CSV file.
for i=1:r
if ~strcmp(name,names{i})
t=i-1;
fileName = "party"+num2str(k)+".csv";
writetable(table(start:t,:),fileName)
start=i;
k= k+1;
name = names{i};
end
end
%Copying the rest of the values to a separate csv file
writetable(table(start:r,:),"party"+num2str(k)+".csv")
I have attached my CSV file on which I have tried this code.
Hope this solution helps with your query.
Thanks
Vishwanath Acharya

Community Treasure Hunt

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

Start Hunting!

Translated by