Ethan Carrés
Ethan Carrés

Reputation: 33

How to pass by reference in Matlab?

this is my first question and I'm a begineer so any help regarding the format of the question will be nice.

I'm programming in Matlab and i want to know if I can add objects to an array and then, when the objects inside the array are modified, get this modification in the original objects. I think it's possible in other languages but in Matlab I cannot find the way.

A simple version of the code will be something like this:

Obj is an Object with several properties.

referenceObj is an instance of Obj which has half of the properties set

obj1...obj5 are instances not initializated of Obj

obj1=referenceObj;
obj2=referenceObj;
obj3=referenceObj;
obj4=referenceObj;
obj5=referenceObj;

arrayOfObj=[obj1 obj2 obj3 obj4 obj5];


for i=1:numel(arrayOfObj)

arrayOfObj(i).someProperty=function;

end

When the code ends the objects in the array have the value of that property set but the originals don't. What I should do?

Thanks a lot and sorry for my bad English =)

Upvotes: 3

Views: 129

Answers (1)

User1551892
User1551892

Reputation: 3364

Class of reference object must inherit from handle like this:

classdef SampleClass < handle    
end

Objects of this class will be reference type. So if you put the objects in array and modify it there then actual object will be modified.

Upvotes: 2

Related Questions