Setting a Value in an Array in a Class
Show older comments
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?
Answers (1)
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 Comments
A. B.
on 19 Sep 2019
You must call it with an output argument,
obj = obj.set_my_array(my_val, my_index)
Alternatively, you can write this as a handle class,
classdef myclass_t < handle %<---NOTICE
properties
my_array double
end
methods
function self = myclass_t( array_size )
self.my_array = zeros(1, array_size);
end %constructor
function set_my_array(self, my_val, my_index) %<---NOTICE
self.my_array(my_index) = my_value;
end
end
end
but make sure you know how handle classes work, and how they behave differently from value classes:
Guillaume
on 19 Sep 2019
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
on 19 Sep 2019
Yep. I've made the appropriate edits.
Categories
Find more on Use Prebuilt MATLAB Interface to C++ Library in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!