Using obj within function without passing it

6 views (last 30 days)
I have a number of class methods that use self (or obj) within the code. The online documentation indicates I do not need to pass obj to the function to use it within, but my code does not work without passing it.
For clarity in case it is an issue - my class is a derived class of type < handle. Using Matlab 2016b
What I would like is this (with or without returning obj):
function obj = Update2(time)
obj.LastUpdate = time;
end
but creates a new obj instead of using the calling obj (which is a handle to the obj of class that includes the function). The code I end up with (works fine) is below, but it means calling it with MyObject.Update(MyObject, time)... seems kind of wrong/unnecessary.
function Update(obj, time)
obj.LastUpdate = time;
end
My calling functions are below - top one works, bottom does not as it returns a new obj.LastUpdate, not the 'h.' calling obj.LastUpdate.
Pretty sure this can be done... what am I missing...?
h.Update(h,111) % Works
h.Update2(222) % INOP

Accepted Answer

Steven Lord
Steven Lord on 23 Jan 2021
The online documentation indicates I do not need to pass obj to the function to use it within
That is incorrect. See the "Method Calling Syntax" section on this documentation page.
The code I end up with (works fine) is below, but it means calling it with MyObject.Update(MyObject, time)... seems kind of wrong/unnecessary.
If Update is a normal method of a class myClass that accepts two inputs, the object and a number time, and myObject is an instance of myClass then either of these lines are ways to call Update.
Update(myObject, time)
myObject.Update(time)
It's a bit more difficult to understand what's going on by looking only at segments of code out of context. Can you write up a small class that demonstrates the problems you're describing and then show us how you're using that class when you experience the problem?
  1 Comment
Marc Elpel
Marc Elpel on 23 Jan 2021
Thanks for the link.
I wrote the attached to test code.
The first call in the test code works and is better than what I was doing... The difference being I have been using Static methods (IE my format is the second test to "obj = obj.Update2(obj,5)").
The only follow-on question is I had expected just "obj.Update1(999);" to work as it is acting on the calling OBJ which (I thought) should not need to be passed back. Is there a way to do that which I missed or is the first funciton call below the optimized method?
% Function calls - no params
obj = obj.Update1(2); % Ordinary method
disp(['obj = obj.Update1(2); ',num2str(obj.x)]);
obj = obj.Update2(obj,5); % Static Method
disp(['obj = obj.Update2(obj,5); ',num2str(obj.x)]);
obj.Update2(obj,5);
disp(['obj.Update2(obj,5); ',num2str(obj.x)]);

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!