Search code examples
matlabclassevalcell-array

Create (class object) variable from string: Matlab


Say there is a cell array

A = {'objA', 'objB', 'objC'}

I want to have its members as instances of MyClass (see below) in Matlab. I couldn't get genvarname or eval to work for this.

Essentially I want loop through the array of names, A, and create a MyClass object for each member. This should result in the objects objA, objB and objC.

classdef MyClass
    properties
       something
       name
    end    
    methods
        function object = MyClass(name)
             object.name  = name;
        end
    end
end

Solution

  • You can define an instance of your user defined class objA using

    objA = MyClass('objA')
    >> objA = MyClass with properties:
    >>        something: []
    >>             name: 'objA'      
    

    So to create this from a string, use eval

    ObjectName = 'objA';
    % We want     objA = MyClass('objA')
    % Equivalent: eval('objA = MyClass(''objA'')')
    % To use the actual name from the variable instead of hard-coding, this becomes:
    eval([ObjectName, '= MyClass(''', ObjectName, ''')'])
    

    Note you must include quotes around the ObjectName variable when passing it into MyClass so that it is passed as a string. To include quotes within a string, you must "escape" them using another quote. This is why we get ''' inside the eval statement.

    To do this on an array, we can use a simple loop

    A = {'objA', 'objB', 'objC'};
    for ii = 1:numel(A)
       eval([A{ii}, '= MyClass(''', A{ii}, ''')']) 
    end 
    

    However, see the MATLAB documentation for Alternatives to the eval function, because it's really not best practise to do this anyway. You're far better off not naming the variables like this. Store them, for example, in a cell array instead where you know the name for later access.

    Objects = cell(1,3);
    for ii = 1:numel(A)
        Objects{ii} = MyClass(A{ii});
    end
    

    You can see this code is much cleaner, easier to debug, and your objects are all stored neatly in a cell array of MyClass objects.