Search code examples
matlaboopcell-array

Cell array assignment result returns to ans `object` instead of expected object `obj`


I had trouble while deciding the title which should be simple and expressive enough. If you can simplify the title, please go ahead and edit it.


I have a Modelclass in which I have a method for adding a node.flow.Pipe object into Model's nodeArray (which is a cell array).

classdef Model

    properties

        nodeArray = {} 

    end

    ...        

    methods

        function result = Model()

        end

        function obj = addNode(obj, node)
            size = numel(obj.nodeArray);
            obj.nodeArray{size+1} = node;
        end

    ...
    end        
end

When I create a Model object and node.flow.Pipe object and then use Model's addNode(node) method, instead of adding a node to that object, Matlab creates a new object ans.

>> newModel = Model

newModel = 

  Model with properties:

                       nodeArray: {}
                   numberOfNodes: 0
                   stateVariable: []
          numberOfStateVariables: 0
            steadyStateEquations: []
    numberOfSteadyStateEquations: 0

>> newModel.addNode(node.flow.Pipe)

ans = 

  Model with properties:

        nodeArray: {[1×1 node.flow.Pipe]}
    numberOfNodes: 1

>> newModel.nodeArray

ans =

  0×0 empty cell array

What am I doing wrong?


Solution

  • By default, all classes in MATLAB are value classes and are copied (by value) whenever you perform an assignment. In order to access classes my reference, you need to inherit from MATLAB's built-in handle class.

    classdef Model < handle
    

    There is an extensive description of the difference between handle and value classes in the documentation.