Entries in array of class instances affecting others in my array

1 visualización (últimos 30 días)
I can't understand why changing instances of a class in an array effect the other entires.
An example of how this works is as follows:
I create a class as follows in one file:
classdef Terminal < handle
properties
Point_1=[]
Point_2=[]
end
end
And wish to make an array where the entires are instances of this class which I create in another file:
%The line below is to make an array with 3 entires all of which are instances of the class Terminal
Terminal_array(1:3)=Terminal
Terminal_array(1).Point_1=1;
%If I call here 'Terminal_array(1).Point_1' the output is 1
Terminal_array(2).Point_1=2;
Terminal_array(3).Point_1=3;
Terminal_array(1).Point_1
If I call Terminal_array(1).Point_1 at the bottom it is 3 instead of the desried 1. I can't understand why this is happening.
Any help or advice would be appriciated.

Respuesta aceptada

Steven Lord
Steven Lord el 5 de Abr. de 2020
You're assigning the same handle object to all three elements of Terminal_array. That means changing one of the elements of Terminal_array will change all of them. You can see that they refer to the same object using the == operator as described on this documentation page.
Terminal_array(1:3) = Terminal;
Terminal_array(1) == Terminal_array(2) % true
Terminal_array(1) == Terminal_array(3) % true
If you created the elements of the array through separate calls to the constructor, they would not refer to the same object.
Terminal_array2(1) = Terminal;
Terminal_array2(2) = Terminal;
Terminal_array2(3) = Terminal;
Terminal_array2(1) == Terminal_array2(2) % false
Terminal_array2(1) == Terminal_array2(3) % false
Terminal_array2(2) == Terminal_array2(3) % false

Más respuestas (0)

Categorías

Más información sobre Construct and Work with Object Arrays en Help Center y File Exchange.

Productos


Versión

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by