Clear Filters
Clear Filters

Referencing objects from one cell array to another cell array

2 views (last 30 days)
Let's have a cell array of multiple objects.
Three objects are type of classdef ClassA.
Two objects are type of classdef ClassB with property named "value" initialized to 0 in their constructor.
cellArray1{1} = ClassA();
cellArray1{2} = ClassB(); % this is desired object with public variable value = 0
cellArray1{3} = ClassA();
cellArray1{4} = ClassB(); % and this is desired object with public variable value = 0
cellArray1{5} = ClassA();
I want to create another cell array which contains only elements type of ClassB BUT those elements must be added by reference from cellArray1.
If I do this
cellArray2{1} = cellArray1{2}; % adding object on index 2
cellArray2{2} = cellArray1{4}; % adding object on index 4
and change value in object from cellArray2 to 5
cellArray2{1}.value = 5;
and display the value of both objects from cellArray1 and cellArray2
disp(cellArray1{2}.value); % this displays 0
disp(cellArray2{1}.value); % this displays 5
the result is 5 and 0 not the 5 and 5!!!
No matter what I am doing, there is no reference connection between those two objects, which means that the "hard copy" is passed, not the "shallow copy".
If I recreate this code for example in Python 3 it works as I wish but not in MATLAB.
Is it possible to do this at all?

Answers (1)

Vatsal
Vatsal on 1 Mar 2024
Hi,
In MATLAB, assigning an object to a variable or to a cell of a cell array results in the creation of a new copy of that object. This is why when the value property of the object in 'cellArray2' is modified, it does not impact the corresponding object in 'cellArray1'.
To have two variables or cell array cells refer to the same object, handle classes can be utilized. Handle classes in MATLAB exhibit reference behavior, meaning when a handle object is copied, MATLAB creates a new handle to the existing object instead of duplicating the object itself.
Below is an example demonstrating the use of handle classes to attain the desired behavior:
classdef ClassB < handle
properties
value = 0;
end
end
cellArray1{1} = ClassA();
cellArray1{2} = ClassB(); % this is desired object with public variable value = 0
cellArray1{3} = ClassA();
cellArray1{4} = ClassB(); % and this is desired object with public variable value = 0
cellArray1{5} = ClassA();
cellArray2{1} = cellArray1{2}; % adding object on index 2
cellArray2{2} = cellArray1{4}; % adding object on index 4
cellArray2{1}.value = 5;
disp(cellArray1{2}.value); % this displays 5
disp(cellArray2{1}.value); % this displays 5
I hope this helps!

Categories

Find more on Construct and Work with Object Arrays in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!