Sum cumulative value from all files that is summoned in a loop

5 ビュー (過去 30 日間)
SRRellum
SRRellum 2022 年 4 月 20 日
コメント済み: SRRellum 2022 年 4 月 20 日
I want to add the row length of the variable 'time' in a file (length(dataset.time)) from multiple datasets that are summoned in a loop. My setup is a follows:
datafolder = ' Z:\Projects\data';
file = dir(datafolder);
for i = 3:105
patient = load(strcat(datafolder,'\',file(i).name));
dataset = patient.table
row_length = length(dataset.time)
sum_length = ?
For now, ' row_length' only outputs the number of rows from the last dataset.
How do I add the total number of rows from dataset 3:105?
Hope you can help
  2 件のコメント
Stephen23
Stephen23 2022 年 4 月 20 日
編集済み: Stephen23 2022 年 4 月 20 日
SRRellum
SRRellum 2022 年 4 月 20 日
Thanks, good point. This was indeed the easy way out. I will change it

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

採用された回答

Davide Masiello
Davide Masiello 2022 年 4 月 20 日
Inside the loop write
row_length(i) = length(dataset.time);
After the loop, you can calculate the summ of all lengths with
sum_length = sum(row_length);
  1 件のコメント
SRRellum
SRRellum 2022 年 4 月 20 日
Thanks for yout help. It works, however it gives the message to consider preallocating. Will look into that.

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

その他の回答 (1 件)

David Hill
David Hill 2022 年 4 月 20 日
datafolder = ' Z:\Projects\data';
file = dir(datafolder);
row_length = 0;
for i = 3:105
patient = load(strcat(datafolder,'\',file(i).name));
dataset = patient.table
row_length = row_length+length(dataset.time)
end
  1 件のコメント
Stephen23
Stephen23 2022 年 4 月 20 日
編集済み: Stephen23 2022 年 4 月 20 日
Fragile/buggy code:
for i = 3:105
Lets try it with some simple, perfectly valid filenames:
csvwrite('+new.txt',1)
csvwrite('-old.txt',1)
csvwrite('test.txt',1)
dir()
+new.txt -old.txt . .. test.txt
Fragile at best, buggy at worst.

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

カテゴリ

Help Center および File ExchangeMATLAB についてさらに検索

タグ

製品


リリース

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by