Filter löschen
Filter löschen

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

5 Ansichten (letzte 30 Tage)
Jaeseok am 15 Jan. 2022
Kommentiert: Jaeseok am 26 Mär. 2022
classdef myClass
function this_ = myClass(argin1_, argin2_) % constructor
this_.prop1 = argin1_ + argin2_;
function setter1(argin)
prop1_ = argin + 1;
function this_ = setter2(this_, argin)
this_.prop1 = argin + 1;
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.

Akzeptierte Antwort

Prince Kumar
Prince Kumar am 20 Jan. 2022
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:
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
Number = 1
For more information please refer the following resources:
Hope this helps
  3 Kommentare
Jaeseok am 26 Mär. 2022
very nice, THANK YOU.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (1)

per isakson
per isakson am 20 Jan. 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.


Mehr zu Properties finden Sie in Help Center und File Exchange




Community Treasure Hunt

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

Start Hunting!

Translated by