From: Quoc Nguyen on
Hi everyone,

I am new to object-oriented programming. Please help.

My class is defined as follows:

-------------------------
(myclass.m)

classdef myclass
properties
a = [];
end

methods
function obj = myclass(n)
obj.a = n;
end
function y = inc(obj)
obj.a = obj.a + 1;
y = obj.a;
end
end
end
-------------
(workspace)

>> x = myclass(1);
>> y = inc(x)

y = 2

>> x.a

ans = 1

---------

In the m-code above, I expect that x.a is equal to 2 after executing y = inc(x).

How can I modify the code so that whenever the method inc() is executed, the property a is also updated according to the command "obj.a = obj.a + 1;" ?

Thanks
From: Andy on
"Quoc Nguyen" <benkuo01(a)gmail.com> wrote in message <i22a5m$lp2$1(a)fred.mathworks.com>...
> Hi everyone,
>
> I am new to object-oriented programming. Please help.
>
> My class is defined as follows:
>
> -------------------------
> (myclass.m)
>
> classdef myclass
> properties
> a = [];
> end
>
> methods
> function obj = myclass(n)
> obj.a = n;
> end
> function y = inc(obj)
> obj.a = obj.a + 1;
> y = obj.a;
> end
> end
> end
> -------------
> (workspace)
>
> >> x = myclass(1);
> >> y = inc(x)
>
> y = 2
>
> >> x.a
>
> ans = 1
>
> ---------
>
> In the m-code above, I expect that x.a is equal to 2 after executing y = inc(x).
>
> How can I modify the code so that whenever the method inc() is executed, the property a is also updated according to the command "obj.a = obj.a + 1;" ?
>
> Thanks

I'm not at MATLAB right now, so I can't check. But I believe if you make your class a subclass of the handle class, this will do what you expect.
From: Quoc Nguyen on
Hi Andy,

It works.

Thank you so much!