How to use writetable in a for loop

Hi everyone,
I want to write a script that, for all files in my folder, selects a specific value out of a table and puts them together in one new table. I am using a for loop including the writetable command, but it creates a new file containing only the value of the last iteration. What am I doing wrong?
volumeTable = dir('*properties_aparc.mat') %% here I select the files I need out of my folder
for k = 1:length(volumeTable);
baseFilename = volumeTable(k).name;
fullFilename = fullfile(volumeTable(k).folder,baseFilename);
load(fullFilename);
T = regionPropertiesTable(31,4) %% Select row 31, column 4 from the regionPropertiesTable
writetable(T)
end
When I use regionPropertiesTable(x,y) outside of this code, it gives me a 1x1 table. I want to add the 1x1 tables of all my participants together into one file (.txt is fine).
Thanks in advance for your time! I am relatively new to MatLab.

 採用された回答

VBBV
VBBV 2022 年 3 月 25 日

1 投票

T{k} = regionPropertiesTable(31,4)
Use a cell array for all participants. Later use
writetable(T)
Outside of loop

4 件のコメント

Daisy
Daisy 2022 年 3 月 25 日
Hi VBBV,
Thank you for your fast reply! If I add T{k} I get the following error:
Subscripting into a table using one subscript (as in t(i)) or three or more subscripts (as in t(i,j,k)) is not supported. Always specify a row subscript and a variable subscript, as in t(rows, vars).
Any idea how to get around this error?
Thanks again!
VBBV
VBBV 2022 年 3 月 25 日
Ok. Try with only
writetable(T,'filename.txt','WriteMode','Append')
Ignore the previous line
Daisy
Daisy 2022 年 3 月 25 日
This one gives me the error 'Invalid parameter name: WriteMode'
Daisy
Daisy 2022 年 3 月 28 日
Hi VBBV, I want to thank you again for your help, I solved my issue :)
As you suggested, I created a cell array and used the writetable command including 'WriteMode' and 'Append', which now creates a csv file with the values I need from the tables in one column. For others struggling like me, here is my code:
volumeTable = dir('*properties_aparc.mat')
for k = 1:length(volumeTable)
baseFilename = volumeTable(k).name;
fullFilename = fullfile(volumeTable(k).folder,baseFilename);
fprintf(1,'Now reading %s\n',fullFilename)
load(fullFilename);
T = regionPropertiesTable(31,4); %% takes ROI volume out of big table and creates a 1x1 table
Volumes{k} = T; %% puts all 1x1 tables in a cell array
writetable(Volumes{k}, 'VolumesTest.csv','WriteMode','Append') %%puts all ROI volumes in 1 column in a .csv file
end

サインインしてコメントする。

その他の回答 (0 件)

質問済み:

2022 年 3 月 25 日

コメント済み:

2022 年 3 月 28 日

Community Treasure Hunt

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

Start Hunting!

Translated by