Writing class in matlab with structures and not allowing user to modify them.
3 views (last 30 days)
Show older comments
I am writing a new class for my project which contains many variables. So I have devided it into many class, lets say-- class "m" has properties m1, m2, m3; class "k" has properties k1,k2,k3, ... and so on). These classes are then imported to a class (say p), as shown below
classdef m
properties
m1,m2,m3
end
end
%%%
classdef k
properties
k1,k2,k3
end
end
%%%
classdef p < m & k
...
end
In this way all the elements are available as p.m1,p.m2,..., p.k1,p.k2,p.k3, ...., etc. Now my problem is that the class "p" has too many variables and looks messy.
Therefore I would like to keep the class in a structured way as-- p.m.m1, p.m.m2, p.m.m3...., p.k.k1, p.k.k2,... etc., For which I have following code.
classdef mod
properties
m= struct('m1',1,'m2',2,'m3',3)
end
end
%%%
classdef kal
properties
k= struct('k1',1,'k2',2,'k3',3)
end
end
%%%
classdef p < mod & kal
...
end
It achieves the above goal, but at the cost of allowing user to add elements to substructure, i.e.
p.s=5 % adding property is not allowed
p.m.s=5 % adding property is ALLOWED..!
Is there any way to stop the user from adding/removing the properties to substructures.
Thanks..!
3 Comments
Matt J
on 17 Apr 2022
lets say-- class "m" has properties m1, m2, m3; class "k" has properties k1,k2,k3, .
Where possible, you should be using a single vector variable, m , not individual scalar variables m1, m2, m3...
Accepted Answer
Matt J
on 23 Apr 2022
Edited: Matt J
on 23 Apr 2022
You can define a set.property method like in the following. This will be inherited by any subclasses.
classdef myclass
properties
m= struct('m1',1,'m2',2,'m3',3)
end
methods
function obj=set.m(obj,val)
if ~isstruct(val)||...
~isempty(setxor(fieldnames(obj.m), fieldnames(val)))
error 'Not allowed'
end
obj.m=val;
end
end
end
>> obj=myclass; obj.m
ans =
struct with fields:
m1: 1
m2: 2
m3: 3
>> obj.m.m1=10; obj.m
ans =
struct with fields:
m1: 10
m2: 2
m3: 3
>> obj.m=5
Error using myclass/set.m (line 12)
Not allowed
>> obj.m.m4=5
Error using myclass/set.m (line 12)
Not allowed
0 Comments
More Answers (1)
Matt J
on 17 Apr 2022
Edited: Matt J
on 17 Apr 2022
Couldn't you make the properties private/protected in mod and kal?
5 Comments
Matt J
on 18 Apr 2022
I don't know what the two cases are that we are talking about. Please explain why SetAcccess and GetAccess method attribute settings will not do what you want.
See Also
Categories
Find more on Class File Organization in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!