Save a non scalar struct

4 ビュー (過去 30 日間)
Deepa Maheshvare
Deepa Maheshvare 2020 年 3 月 5 日
編集済み: per isakson 2020 年 3 月 5 日
I've the following function
function fun(i)
var = true
if var
ss(i).bv = rand(10,1)
if i == 4
pwd
save(fullfile(pwd, 'ss.mat'), 'ss');
end
end
The above function is called as below
for i = 1:4
i
fun(i)
end
The result is loaded,
l = load('ss.mat')
l.ss.bv
ans =
[]
ans =
[]
ans =
[]
ans =
0.8217
0.4299
0.8878
0.3912
0.7691
0.3968
0.8085
0.7551
0.3774
0.2160
I am not sure why the first there indices are empty. I want to store the results for all i.
Any suggestions?

回答 (2 件)

per isakson
per isakson 2020 年 3 月 5 日
編集済み: per isakson 2020 年 3 月 5 日
The variable ss isn't saved between the calls of fun(). For the struct saved, only ss(4).bv is defined.
That's the way Matlab works:
>> clearvars
>> ss(4).bv=17
ss =
1×4 struct array with fields:
bv
>> ss(1).bv
ans =
[]
I failed to find the behaviour described in the documentation. The closest is in Memory Requirements for Structure Array. I replaced [] by 1, 2 and 3.
>> newStruct(25,50) = struct('a',1,'b',2,'c',3);
>> newStruct(1,50)
ans =
struct with fields:
a: []
b: []
c: []
>>
  2 件のコメント
per isakson
per isakson 2020 年 3 月 5 日
Maybe it goes without saying that the code below creates patient(1) and patient(2) with empty fields However, it's not spelled out explicitely for structs (as far as I can see).
clearvars patient
patient(3).name = 'New Name';
patient(3)

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


Bhaskar R
Bhaskar R 2020 年 3 月 5 日
編集済み: Bhaskar R 2020 年 3 月 5 日
Here the MATLAB variable scope and life time plays.
For each iteration of for loop calling in the function fun variable ss is new, so last iteration will be saved as per isakson answer. If you want to work variable as you required then declare variable ss as persistent.
And in your code you have applied if condition i == 4 that also causes the problem, so remove that
function fun(i)
persistent ss
var = true
if var
ss(i).bv = rand(10,1);
save(fullfile(pwd, 'ss.mat'), 'ss');
end
end
This can get you what you want
  1 件のコメント
Deepa Maheshvare
Deepa Maheshvare 2020 年 3 月 5 日
Hi, Many thanks. This helps. And in your code you have applied if condition i == 4 that also causes the problem, so remove that
Could you please explain why this causes problem? Instead of writing to a file for each iteration , I want to write at the final iteration.

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

タグ

製品

Community Treasure Hunt

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

Start Hunting!

Translated by