Blitzkayir
Blitzkayir

Reputation: 67

How to convert string to a function name?

How would I go about converting x = 'abs' Into abs so that I could do z = abs(-5) = 5. Or where x = 'randfunc' where 'randfunc' can be any input string relating to a function.

>> x

x =

abs

>> x(-5)
Subscript indices must either be real positive
integers or logicals.

Upvotes: 3

Views: 140

Answers (1)

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272467

Use str2func:

x = 'abs';
fh = str2func(x);
fh(-5)               % Prints 5

Upvotes: 8

Related Questions