Class method is 'call by value' function, isn't it?
6 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Jaeseok
el 15 de En. de 2022
Comentada: Jaeseok
el 26 de Mzo. de 2022
classdef myClass
properties
prop1
end
methods
function this_ = myClass(argin1_, argin2_) % constructor
this_.prop1 = argin1_ + argin2_;
end
function setter1(argin)
prop1_ = argin + 1;
end
function this_ = setter2(this_, argin)
this_.prop1 = argin + 1;
end
end
end
Matlab editor give me a error message for setter1 method.
It tells me that first input arg must be instance itself, and must be returned after manipulation.
This implies a class method of Matlab is a cal-by-value function.
I have very large fixed size array data as a property of my class,
and want to update a couple of elements in it many times very quickly.
so, definitely I want to avoid 'call by value' function as my method.
What would be a option for me,
Thank you.
0 comentarios
Respuesta aceptada
Prince Kumar
el 20 de En. de 2022
Hi,
One of the input arguments must be an object or array of objects of the defining class. These methods can compute values based on object data, can overload MATLAB built-in functions, and can call other methods and functions.
Either of the following statements is correct syntax for calling a method, where obj is an object of the class defining the methodName method:
obj.methodName(arg);
methodName(obj,arg);
You are creating a "value" class. When you copy a value object to another variable or pass a value object to a function, MATLAB creates an independent copy of the object and all the data contained by the object. The new object is independent of changes to the original object.
You need to create "handle" class.
Instances of classes that derive from the "handle" class are references to the underlying object data. When you copy a "handle" object, MATLAB copies the handle, but does not copy the data stored in the object properties. The copy refers to the same object as the original handle. If you change a property value on the original object, the copied handle references the same change.
Following is the way to create a "handle" class:
classdef NumHandle < handle
properties
Number = 1
end
end
For more information please refer the following resources:
Hope this helps
3 comentarios
Más respuestas (1)
per isakson
el 20 de En. de 2022
"It tells me that first input arg must be instance itself" Yes, Matlab requires that the instance is passed explicitly as in setter2. That applies to both handle and value classes.
"What would be a option for me" Use a handle class.
0 comentarios
Ver también
Categorías
Más información sobre Software Development Tools en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!