MATLAB Answers


Using a string as a command?

Asked by Kavan
on 7 Mar 2013

Let's say I have x=linspace(0,10), and y='x.^2', as a string. How do I tell MatLab to apply y to x? What I am asking is, in the command window, I can type yy=x.^2 to get the desired result. But, I am writing a script and I need to be able to take the string 'x.^2' and tell MatLab yy=x.^2, so I get a yy double that I can plot in the linspace I created. However, simply typing yy=y just creates another string yy='x.^2'.



No products are associated with this question.

3 Answers

Answer by Jing
on 7 Mar 2013

You can do that by using 'eval'. When y is the string, try the following command.



This is not recommended.

on 8 Mar 2013

Why not?

Answer by Andrei Bobrov
on 7 Mar 2013
Edited by Andrei Bobrov
on 7 Mar 2013


str = 'x.^2';
yy = str2func(['@(',char(symvar(str)),')',str]);


x = 0:10;
out = yy(x);


str = 'x^2 - y^2'
k = strcat(symvar(str),',');
k = [k{:}];
yy = str2func(['@(',k(1:end-1),')',vectorize(str)]);


x = 1:10;
y = linspace(5,20,10);
out = yy(x,y);

  1 Comment

Answer by Walter Roberson
on 7 Mar 2013

f = str2func( ['@(x) ' TheString] );
yy = f(x);


Join the 15-year community celebration.

Play games and win prizes!

Learn more
Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

MATLAB Academy

New to MATLAB?

Learn MATLAB today!