Using obj within function without passing it
8 次查看(过去 30 天)
显示 更早的评论
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
0 个评论
采纳的回答
Steven Lord
2021-1-23
The online documentation indicates I do not need to pass obj to the function to use it within
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?
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Handle Classes 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!