Can I detect array index inside setter method?
4 次查看(过去 30 天)
显示 更早的评论
Is there a way to detect the index/position of the setted value inside a new defined setter method?
I mean, if I call
obj.Prop(idx) = val;
that
function set.Prop(obj,val)
if % idx > 5
val = ...;
end
obj.Prop = val;
end
does different calculations on specific indices.
THX
In MATLAB documentation is a short description I don't really understand________________________________________
Access Methods and Properties Containing Arrays
You can use array indexing with properties that contain arrays without interfering with property set and get methods.
For indexed reference:
val = obj.PropName(n);
MATLAB calls the get method to get the referenced value.
For indexed assignment:
obj.PropName(n) = val;
MATLAB:
- Invokes the get method to get the property value
- Performs the indexed assignment on the returned property
- Passes the new property value to the set method
2 个评论
Image Analyst
2020-7-18
I don't understand the question. In essence you say you want to "detect the index/position of the setted value" but then you say you did this:
obj.Prop(idx) = val;
so is idx NOT the index/position of the value you wanted to set? You already know this index value or else you could not have used it like that. So why do you think you need to "detect" it?
采纳的回答
Tommy
2020-7-18
"For indexed assignment:
obj.PropName(n) = val;
MATLAB:
- Invokes the get method to get the property value
- Performs the indexed assignment on the returned property
- Passes the new property value to the set method"
If I am understanding this correctly, then
obj.PropName(n) = val;
is essentially similar to
myProp = obj.PropName; % get method
myProp(n) = val;
obj.PropName = myProp; % set method
so that neither the get method nor the set method ever sees n.
You could compare obj.Prop to val within your set method before you set obj.Prop so that you can determine which value is being changed, but that doesn't seem like a very good solution. You could also look into overloading subsasgn for your object, which might do the trick (requiring that you explicitly call subsasgn within your class rather than use '()' and '.', see here for explanation). Though I hope I'm overlooking a simpler solution.
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Whos 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!