Setting a Value in an Array in a Class

12 次查看(过去 30 天)
A. B.
A. B. 2019-9-19
评论: Matt J 2019-9-19
classdef myclass_t
properties
my_array double
end
methods
function self = myclass_t( array_size )
self.my_array = zeros(1, array_size);
end %constructor
function self = set.my_array(self, my_val, my_index)
self.my_array(my_index) = my_value;
end
end
end
I want to set the value of my array with the value my_value at my_index. Lets assume there are no type errors.
However when I do this, I get the following error: Set Methods must have exactly two inputs
How can I set the value of this array at the desired index?
  3 个评论
A. B.
A. B. 2019-9-19
I don't know. I just want to set the damn value lol
Matt J
Matt J 2019-9-19
What's wrong with simply doing a direct assignment to my_array all the time,
obj=myclass_t(10);
obj.my_array(5)=6;

请先登录,再进行评论。

回答(1 个)

Matt J
Matt J 2019-9-19
编辑:Matt J 2019-9-19
Use an ordinary method:
classdef myclass_t
properties
my_array double
end
methods
function self = myclass_t( array_size )
self.my_array = zeros(1, array_size);
end %constructor
function self = set_my_array(self, my_val, my_index) %<---changed set. to set_
self.my_array(my_index) = my_value;
end
end
end
  4 个评论
Guillaume
Guillaume 2019-9-19
Careful there! That set method for the handle class is not valid.
Property set methods do not support indexing into the property. You have to replace the whole array.
So with the value class, a valid set method would be
function self = set.my_array(self, value)
self.my_array = value;
end
and for a handle class, the equivalent:
function set.my_array(self, value)
self.my_array = value;
end
Note that in both case, you never call the set method directly. It's invoked for you by matlab when you do:
obj.my_array = [1, 2, 3]; %will invoke set.my_array(obj, [1, 2, 3]) if the method is defined
With this particular example, the set method is completely pointless. It's useful if you want to do additional validation or something more complex than just assigning the input to the property.
If you do want to index into the property, then either don't define a set method so you can access directy the public property, or create a normal method as per matt's first example.
Matt J
Matt J 2019-9-19
Yep. I've made the appropriate edits.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Construct and Work with Object Arrays 的更多信息

产品


版本

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by