2

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?

3 Answers 3

2

Got it. I found that this:

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

Does the job.

Sign up to request clarification or add additional context in comments.

Comments

0

eval can also be used:

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

1 Comment

str2func is still much preferrable.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.