How do I invoke my property set method?

15 次查看(过去 30 天)
Hi all,
My code is like this
classdef A
properties
posi(3,1) double
velo(3,1) double
acce(3,1) double
end
methods
function obj = A(r, v, a) %Constructor
% code
end
function fun1
% code
d
end
function obj = set.acce (obj, value)
if (%conditions)
% code to modify value
obj.acce = value;
else error ('Error message')
end
end
end
end
I'm not sure how I would call the set.acce function on the commands window as well as in the fun1 method.
I've tried doing
objX = A(%parameters);
objX.acce = someValue;
But this directly sets the value of objX.acce to someValue instead of calling the set.acce function to modify someValue first. Both
objX.set.acce(value);
and
set.acce(objX,value);
would throw error messages. How would I fix this? Thank you!

回答(1 个)

per isakson
per isakson 2019-11-21
编辑:per isakson 2019-11-21
Doc says: You cannot call property access methods directly. MATLAB calls these methods when you access property values.
"objX.acce = someValue;" should work!
Try
>> obj.acce = [1;2;3];
>> obj.acce
ans =
1
2
3
>>
Capture.PNG
  3 个评论
per isakson
per isakson 2019-11-21
"When it should have been" a statement like this one needs a reference to the Matlab documentation.
per isakson
per isakson 2019-11-21
编辑:per isakson 2019-11-21
Doc on Validate Property Values says The value assigned to the property must conform to the specified size or be compatible with the specified size.
"error if a 2x1 vector" doesn't conform to (3,1).
>> obj.acce = [1;2]
Error setting property 'acce' of class 'A':
Size of value must match specified dimensions 3×1 or be scalar.
Size is obviously checked before the set.method is invoked.
"MATLAB never calls my set method at all" In the simple example of my answer it definately does as illustrated by the halt at the breakpoint.
This is expected behavior
>> obj.acce = [11;12;13];
>> obj.acce = 1;
>> obj.acce'
ans =
1 1 1
>>
A scalar is compatible with (3,1). See Compatible Array Sizes for Basic Operations

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Whos 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by