Add structs in a saved array of structures

Hello,
I have a function (fun1) which generates several results (r1,r2,r3...). I organise them in a struct.
results=struct('results1',{r1},'results2',{r2},'results3',{r3},...);
This struct is the output of the funtion.
I have to run this same function for several variables and I want to keep all the results in the same array of structs. Therefore could I do:
results(1)=fun1(variable1,otherinputs);
results(2)=fun1(variable2,otherinputs);
results(3)=fun1(variable3,otherinputs);
...
However, the function deals with huge sets of data so it can take on the order of 45 minutes to run, and I have to run it more than 20 times. Is there any way to save the output struct so that each time that I run the function it adds the output to the previous ones? I mean to do something similar to what I do in the workspace but directly in a .mat file.
Thanks!

 採用された回答

Mohammad Sami
Mohammad Sami 2020 年 1 月 28 日

1 投票

You can use the matfile function to write directly to a mat file
a = matfile('newfile.mat','Writable',true);
n = 10;
for i = 1:n
% your code
a.mystruct(i,1) = struct('abc',123,'def',456);
end
clear a;

6 件のコメント

Miquel
Miquel 2020 年 1 月 28 日
編集済み: Miquel 2020 年 1 月 28 日
Thanks!
So, to check that I understood: In my example the loop should be the following, right?
n = numberofvariables;
for i = 1:n
a.results(i,1)=fun1(variable(i),otherinputs(i));
end
Mohammad Sami
Mohammad Sami 2020 年 1 月 28 日
Yes. that should work, as long as the output is always a struct with same fieldnames.
Miquel
Miquel 2020 年 1 月 28 日
Cool, yes. Thanks :)
Miquel
Miquel 2020 年 1 月 28 日
BTW, is it advisable to start the loop in the end for allocation issues (as Jan always remarks in the forum)? Or is this not the case with structs?
n = numberofvariables;
for i = n:-1:1
a.results(i,1)=fun1(variable(i),otherinputs(i));
end
Stephen23
Stephen23 2020 年 1 月 28 日
編集済み: Stephen23 2020 年 1 月 28 日
Unless the structure itself** is huge, iterating in reverse is unlikely to make much difference. But you can experiment and tell us the results.
** not the data it contains!
Miquel
Miquel 2020 年 1 月 28 日
Ok, thanks. No, I generate 2 stucts that are only 7 fields and around 20... rows? So I guess it should make almost no difference. And I will be using the computer most of the time while Matlab is running. Thanks both!

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

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeStructures についてさらに検索

製品

リリース

R2018b

タグ

質問済み:

2020 年 1 月 27 日

コメント済み:

2020 年 1 月 28 日

Community Treasure Hunt

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

Start Hunting!

Translated by