OOP in Matlab: Create Instance Using Class Name from String Variable

This short tutorial presents an example of OOP in Matlab, showing how to determine class name from a string variable when creating an instance.

Suppose we already defined two classes, ClassA and ClassB. Following code shows how to get class name from a string variable using the feval() function.

if x > 0
    ClassName = 'ClassA';
else
    ClassName = 'ClassB';
end
TheInstance = feval(ClassName, AllRequiredArguments)

In essence, here we use function handle to call the class constructor, which is equivalent to following

if x > 0
    ClassName = @ClassA;
else
    ClassName = @ClassB;
end
TheInstance = ClassName( AllRequiredArguments)

 

Tags
Subject
Category
Coding language