Save a non scalar struct

4 次查看(过去 30 天)
Deepa Maheshvare
Deepa Maheshvare 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 个评论
Stephen23
Stephen23 2020-3-5
"Any unspecified fields for new structs in the array contain empty arrays."
per isakson
per isakson 2020-3-5
编辑: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.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Structures 的更多信息

标签

产品

Community Treasure Hunt

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

Start Hunting!

Translated by