Struct variables don't save

I have various matrices and I'd like them to be part of a struct. Each matrix is computed on its own, assigned to the struct, then the workspace is cleared except for the struct and its variables (clearvars -except matrices). My problem is when the program is finished, only the last variable in the struct is saved/exists. My syntax looks something like this:
matrices=struct; %initialize the struct
Next I compute the matrix and assign it
matrices.s1=matrix; %assign
Then I compute the next matrix and assign it
matrices.s2=matrix; % assign
I do this for about 30 matrices and when the program finishes, only one variable is in the struct - the most recent one. How can I overcome this? Many thanks.

댓글 수: 3

Geoff Hayes
Geoff Hayes 2015년 11월 17일
Cary - what are the different fields for your struct? Are you really creating one for each matrix named s1, s2, etc.? I think that it would be more practical to just create a single field that will be a cell array of the matrices (assuming that not all matrices have the same dimension).
As for why there is only one variable remaining in your struct, please post the code that you have written (or enough of it so that we can get an idea of what you have done). While the above pseudo code is helpful, it doesn't tell us everything.
Walter Roberson
Walter Roberson 2015년 11월 17일
Try commenting out the "clearvars" and seeing if that works.
Stephen23
Stephen23 2015년 11월 18일
편집: Stephen23 2015년 11월 18일
You should probably switch to using a non-scalar structure, which would simplify assigning the values to the fields. Using non-scalar structures makes accessing the data much easier than using numbered field names!
Examples of using non-scalar structures:
Example Code:
>> A(1).data = 4;
>> A(2).data = 5;
>> A(3).data = 6;
OR
>> A = struct('data',{4,5,6});
And then access the field of any element of the structure using indexing and the fieldname:
>> A(2).data
ans = 5
Which means you can get the sum of all of the elements using this simple code:
>> sum([A.data])
ans = 15

댓글을 달려면 로그인하십시오.

답변 (1개)

Image Analyst
Image Analyst 2015년 11월 17일

0 개 추천

Just use the debugger and find out where the earlier fields disappear. For example, so you have all 30 fields just before the call to clearvars and only one, s30, after you call it? Or when you assign matrices.s2, does matrices.s1 vanish at that point? If you knew how to use the debugger, this could be very straightforward. http://blogs.mathworks.com/videos/2012/07/03/debugging-in-matlab/

카테고리

도움말 센터File Exchange에서 Structures에 대해 자세히 알아보기

태그

질문:

2015년 11월 17일

편집:

2015년 11월 18일

Community Treasure Hunt

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

Start Hunting!

Translated by