Change struct property values in a class

조회 수: 4 (최근 30일)
Olf
Olf 2014년 10월 28일
답변: Olf 2014년 11월 6일
Hi, I have a problem with using a struct as property of a value class. It seems I cannot change the values of fields (or add new fields).
The simplest example is as follows:
classdef testclass
properties
struct_prop=struct;
end
methods
function obj = change_struct_prop(obj, val)
obj.struct_prop.field1 = val;
end
end
end
Trying to change the struct_prop doesn't work:
>> a=testclass;
>> a.change_struct_prop(2);
>> a.struct_prop
ans =
field1: []
>>
Is there any way to manipulate a class property that is a struct (without having to define a separate class for it)? Defining the struct_prop fields in the initialisation function didn't help either.
Thanks a lot,
Olf

채택된 답변

per isakson
per isakson 2014년 10월 28일
편집: per isakson 2014년 10월 29일
Replace
classdef testclass
by
classdef testclass < handle
and search the help for "Comparing Handle and Value Classes"
&nbsp
In response to the comment
If a value class, replace
>> a.change_struct_prop(2);
by
>> a = a.change_struct_prop(2);
and read the help on the comparison of value and handle classes
  댓글 수: 2
Olf
Olf 2014년 10월 28일
I tried handle classes before, however I want to create an array of my class which I iteratively define by copying the (n-1)th element to the (n)th element and apply changes to that. If the class is a handle class, all instances will be identical which is not desired. Any way to get around this?
per isakson
per isakson 2014년 10월 28일
See addition to answer

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

추가 답변 (1개)

Olf
Olf 2014년 11월 6일
I found a solution that seems to have solved the issue. Instead of inheriting from the handle class I let it inherit from matlab.mixin.Copyable This gives the features from the handle class and also comes with a copy method.
classdef testclass < matlab.mixin.Copyable ...

카테고리

Help CenterFile Exchange에서 Scope Variables and Generate Names에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by