Save a non scalar struct

조회 수: 6 (최근 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
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