Reputation: 21
I'm new to object oriented programming in matlab and am having some trouble modifying some of my properties from within my class constructor. My class looks something like
classdef kENot
properties
Sys;
end
methods
function obj=kENot(Sys)
%Constructor
obj.Sys=Sys;
obj.eyePrime
end
function obj=eyePrime(obj)
obj.Sys.IPrime=5
end
end
end
Then from the comand line I call that constructor as
Sys.Iprime=4;
classObj=kENot(Sys);
disp(classObj.Sys.Iprime)
And matlab prints 4. What I want is for the value of classObj.Sys.Iprime to update during the call to obj.eyePrime in t he constructor, but that doesn't see to be happening. Any thoughts?
Upvotes: 2
Views: 328
Reputation: 9696
For completeness, making a handle class is not the only way to solve this.
As long as kENot
is not a handle class, you'll always have to assign the output of methods that change the object to the variable holding the instance.
In your current implementation eyePrime
returns the modified obj
. But you're not using the returned value.
So, you could change your constructor to:
function obj=kENot(Sys)
%Constructor
obj.Sys=Sys;
obj = obj.eyePrime();
end
Granted, this is pretty awkward syntax compared to all other object oriented programming languages and that's presumably why handle classes are favoured here.
As usual, there's pretty good documention from mathworks on this:
http://www.mathworks.de/de/help/matlab/matlab_oop/comparing-handle-and-value-classes.html
Upvotes: 2
Reputation: 238051
First I think that insead of obj.Sys.IPrime=5
you should have obj.Sys.Iprime=5
, i.e. small 'p'. Second, I think you need to make handle
class.
classdef kENot < handle
properties
Sys;
end
methods
function obj=kENot(Sys)
%Constructor
obj.Sys=Sys;
obj.eyePrime();
end
function obj = eyePrime(obj)
obj.Sys.Iprime=5;
end
end
end
Upvotes: 1