Setting a Value in an Array in a Class

16 visualizaciones (últimos 30 días)
A. B.
A. B. el 19 de Sept. de 2019
Comentada: Matt J el 19 de Sept. de 2019
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 comentarios
A. B.
A. B. el 19 de Sept. de 2019
I don't know. I just want to set the damn value lol
Matt J
Matt J el 19 de Sept. de 2019
What's wrong with simply doing a direct assignment to my_array all the time,
obj=myclass_t(10);
obj.my_array(5)=6;

Iniciar sesión para comentar.

Respuestas (1)

Matt J
Matt J el 19 de Sept. de 2019
Editada: Matt J el 19 de Sept. de 2019
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 comentarios
Guillaume
Guillaume el 19 de Sept. de 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
Matt J el 19 de Sept. de 2019
Yep. I've made the appropriate edits.

Iniciar sesión para comentar.

Categorías

Más información sobre Construct and Work with Object Arrays en Help Center y File Exchange.

Productos


Versión

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by