MATLAB Answers

how to import multiple csv file column-oriented with tabularTextDatastore

4 views (last 30 days)
Deniz BINGOLBALI
Deniz BINGOLBALI on 2 Feb 2021
Answered: Sindhu Karri on 5 Feb 2021
Hello everyone,
I'm really new in Matlab, I have multiple csv file in different folders. One folder correspond to one patient, so I wanted to import these csv file into one. Let me explain:
ROI rh
______________________________ ______
'Lateral-nucleus' 785.79
'Basal-nucleus' 512.47
'Accessory-Basal-nucleus' 280.36
'Anterior-amygdaloid-area-AAA' 63.445
'Central-nucleus' 53.417
'Medial-nucleus' 34.717
'Cortical-nucleus' 29.601
'Corticoamygdaloid-transitio' 186.98
'Paralaminar-nucleus' 58.18
'Whole_amygdala' 2005
This a one csv file name "Allfile.csv' and I have this file for every patients (with different values ofc) with the same form (the same first column , 'ROI', with the exact name and a second column called 'rh'). So I wanted to add the second column of every other patients "horizontally" to finally have one big file with these two columns.
There is my code to export these files using tabularTextDatastore:
ThePath= gdir('/network/.../freesurfer7', '^20')
mri = get_subdir_regex( ThePath, '^mri')
file = get_subdir_regex_files (mri, 'Allfile.csv')
ds = tabularTextDatastore(file)
ds.SelectedVariableNames = { 'ROI','rh'}
T = readall(ds)
this is the beginning of the output, each part (delimited with blue line) corresponds to one patient and I was "added" vertically.
Sorry for this long post but I really could use some help please. (I use MATLAB R2017b)
Have a good night

Answers (1)

Sindhu Karri
Sindhu Karri on 5 Feb 2021
Hii,
Assuming that you have all .csv in same folder that is included in current MATLA B path ..The below attached code will be helpful
mkdir myfolder
copyfile patient1.csv myfolder
copyfile patient2.csv myfolder
copyfile patient3.csv myfolder
a=dir ('myfolder');
j=1;
opts = detectImportOptions(a(3).name);
opts.SelectedVariableNames=opts.VariableNames{1};
C=readtable(a(3).name,opts);
for i=3:size(a,1)
opts1 = detectImportOptions(a(i).name);
p=int2str(j);
opts1.VariableNames{2}=strcat(opts1.VariableNames{2},p);
opts1.SelectedVariableNames=opts1.VariableNames{2};
A=readtable(a(i).name,opts1);
C=[C,A];
j=j+1;
end
Note:If you have only .csv files in the folder included in current MATLAB path ,you can comment out 1-4 lines of code and replace 'myfolder' in line 5 with current folder name.
Refer to below link for more details
Hope this helps!

Community Treasure Hunt

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

Start Hunting!