casparjespersen
casparjespersen

Reputation: 3830

Calling an object dynamically in Matlab

Say I have the following variable

myClassName = 'myClass';

And I want to call an instance of the myClass constructor function, ie.

myObject = myClass(arg1, arg2, ..., argn);

Let's say I want to call it using myClassName.

myObject = (myClassName)(arg1, arg2, ..., argn);      % something like that

How do I do that?

Upvotes: 2

Views: 74

Answers (3)

Pursuit
Pursuit

Reputation: 12345

Does the initial variable myClassName actually need to be a string? I would implement this as:

myClassName = @myClass;
myObject = myClassName(arg1, arg2, arg3);

This is pretty similar to using the str2func call from your selfanswer, bit without the string operations which make some people (for example, me) feel wrong.

Upvotes: 0

Andrey Rubshtein
Andrey Rubshtein

Reputation: 20915

eval can also be used:

eval([myClassName '(arg1,arg2,arg3)']);

Upvotes: 0

casparjespersen
casparjespersen

Reputation: 3830

Got it. I found that this:

myFunc = str2func(myClassName);
myClass = myFunc(arg1, arg2, ..., argn);

Does the job.

Upvotes: 2

Related Questions