Copying option structs by value instead of reference
조회 수: 12 (최근 30일)
이전 댓글 표시
Here is an example using bodeoptions, but this is probably a much more basic problem:
% Create a struct with default values
opt1 = bodeoptions;
% Change a value
opt1.MagScale = 'log'
% Now generate another (?) struct with the same options
opt2 = opt1;
% Change the value in the original struct back to default
opt1.MagScale = 'linear'
% Surprise! The value is changed back in the 'copy,' too
opt2.Magscale
Similarly, changing anything in opt2 changes opt1, too, so it appears opt2 is not another struct but a reference to the same structure as opt1.
Can anybody tell me what's happening here, and in particular: How would I create a copy of opt1 that I can change without changing opt1, too?
댓글 수: 0
채택된 답변
Guillaume
2014년 8월 18일
Most likely, bodeoptions returns a handle class rather than a structure.
whos opt1
would tell you.
Matlab does not have a built-in way to do deep copy of handle classes. Possibly, the class has a method to do this. You can check with
methods(opt1)
But in any case, what's stopping you from creating your second variable with:
opt2 = bodeoptions;
It'll start out the same as opt1 but will be a different object.
댓글 수: 6
per isakson
2014년 8월 18일
편집: per isakson
2014년 8월 18일
Matlab is hiding something, or uses features, which are not yet documented. With R2013a
>> superclasses(opt1)
No superclasses for class plotopts.BodePlotOptions ...
추가 답변 (1개)
Image Analyst
2014년 8월 18일
Very interesting. It doesn't happen with simpler structures you make on your own:
s1.a = 10;
s1.b = 20;
% Make copy.
s2 = s1
% Change something in the original.
s1.a = 999
% Print to command window;
s1
s2 % s2.a is not 999
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Function Creation에 대해 자세히 알아보기
제품
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!