Azzera filtri
Azzera filtri

Class method is 'call by value' function, isn't it?

7 visualizzazioni (ultimi 30 giorni)
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.

Risposta accettata

Prince Kumar
Prince Kumar il 20 Gen 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 Commenti

Accedi per commentare.

Più risposte (1)

per isakson
per isakson il 20 Gen 2022
See Comparison of Handle and Value Classes. Your myClass is a value class.
"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.

Categorie

Scopri di più su Software Development Tools in Help Center e File Exchange

Prodotti


Release

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by