Writing tables within a for loop

24 ビュー (過去 30 日間)
Carly
Carly 2025 年 1 月 28 日
編集済み: dpb 2025 年 1 月 30 日
Hi all,
I'm trying to make a for loop to process some EEG data. The final output is (1x96) for each participant which is finally working great, however, now I'm having issues writing the data/ looping through the participants. I've attached what the output looks like for one particpant as that is how far I can get. Below is what I'm trying to use unnsuccessfully. Any help is greatly appreciated!
SubjectNum = { '01-02' '01-03' };
resultsFileName = [fullfile(baseDir, 'MATLAB_Output', 'DIVINE.75results.xlsx')];
for k = 1:length(SubjectNum)
.... (whole bunch of steps)
RelativePowerResults = table(ID,channelsLabel,relativeDelta2,relativeTheta2,relativeAlpha2,relativeBeta2,relativeGamma2)
% unstack resulting in (1 row with 96 columns)
RelativePowerResults_Wide = unstack(RelativePowerResults,"relative"+["Alpha2","Delta2","Theta2","Beta2","Gamma2"],'channelsLabel');
if k == 1
% First subject, with variable names
writetable(RelativePowerResults_Wide, resultsFileName, 'Sheet', 1, 'Range', RANGE{k});
else
% For subsequent subjects, write without variable names
writetable(RelativePowerResults_Wide, resultsFileName, 'Sheet', 1, 'Range',RANGE{k}, 'WriteVariableNames', false);
end

回答 (1 件)

Walter Roberson
Walter Roberson 2025 年 1 月 28 日
移動済み: Walter Roberson 2025 年 1 月 29 日
Instead of worrying about the Range arguement, consider the possibility of using 'WriteMode', 'append' which will automatically put the new data at the bottom of all previous data.
  2 件のコメント
Carly
Carly 2025 年 1 月 29 日
移動済み: Walter Roberson 2025 年 1 月 29 日
Hi Walter,
Thanks! I changed it to this based on your advice and it works now!
if nSubject == 1
% First subject, with variable names
writetable(RelativePowerResults_Wide,'Sheet',1,resultsFileName);
else
% For subsequent subjects, write without variable names
writetable(RelativePowerResults_Wide, resultsFileName, 'Sheet', 1,'WriteMode','append', 'WriteVariableNames',false);
dpb
dpb 2025 年 1 月 29 日
編集済み: dpb 2025 年 1 月 30 日
Could cut down code a little by
writetable(RelativePowerResults_Wide,resultsFileName,'Sheet',1,'WriteMode','append', ...
'WriteVariableNames',nSubject==1)
to generate the logic value on the fly instead.
But, the 'WriteMode','append' flag automagically writes the variable names to an empty sheet and then doesn't write the variable names if there are existing data on the sheet so it's superfluous to add it, anyway, and the single form suffices for both first and subsequent writes.
writetable(RelativePowerResults_Wide,resultsFileName,'Sheet',1,'WriteMode','append')

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

カテゴリ

Help Center および File ExchangeEEG/MEG/ECoG についてさらに検索

タグ

製品


リリース

R2024b

Community Treasure Hunt

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

Start Hunting!

Translated by