MATLAB Answers

How do I invoke my property set method?

4 views (last 30 days)
Loc Duong
Loc Duong on 21 Nov 2019
Edited: per isakson on 21 Nov 2019
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!

  0 Comments

Sign in to comment.

Answers (1)

per isakson
per isakson on 21 Nov 2019
Edited: per isakson on 21 Nov 2019
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 Comments

Loc Duong
Loc Duong on 21 Nov 2019
Hi,
My set.acce converts a 1x1 or 2x1 vector into a 3x1 vector before assigning that 3x1 vector to the acce property.
If I try to say
>> obj.acce = 1
ans
1
1
1
When it should have been
ans
1
0
0
It will also throw an error if a 2x1 vector is passed through. So basically MATLAB never calls my set method at all, it's just using the "default set method" (or whatever the equivalent is called in MATLAB).
Thanks
per isakson
per isakson on 21 Nov 2019
"When it should have been" a statement like this one needs a reference to the Matlab documentation.
per isakson
per isakson on 21 Nov 2019
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

Sign in to comment.

Sign in to answer this question.