MATLAB Answers

Save a non scalar struct

3 views (last 30 days)
Deepa Maheshvare
Deepa Maheshvare on 5 Mar 2020
Edited: per isakson on 5 Mar 2020
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?

  0 Comments

Sign in to comment.

Answers (2)

per isakson
per isakson on 5 Mar 2020
Edited: per isakson on 5 Mar 2020
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 Comments

Stephen Cobeldick
Stephen Cobeldick on 5 Mar 2020
"Any unspecified fields for new structs in the array contain empty arrays."
per isakson
per isakson on 5 Mar 2020
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)

Sign in to comment.


Bhaskar R
Bhaskar R on 5 Mar 2020
Edited: Bhaskar R on 5 Mar 2020
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 Comment

Deepa Maheshvare
Deepa Maheshvare on 5 Mar 2020
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.

Sign in to comment.

Sign in to answer this question.

Tags

Products


Translated by