Using a string as a command?

52 ビュー (過去 30 日間)
Kavan
Kavan 2013 年 3 月 7 日
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'.

回答 (3 件)

Jing
Jing 2013 年 3 月 7 日
You can do that by using 'eval'. When y is the string, try the following command.
yy=eval(y);
  2 件のコメント
Walter Roberson
Walter Roberson 2013 年 3 月 7 日
This is not recommended.
Jing
Jing 2013 年 3 月 8 日
Why not?

サインインしてコメントする。


Andrei Bobrov
Andrei Bobrov 2013 年 3 月 7 日
編集済み: Andrei Bobrov 2013 年 3 月 7 日
eg:
str = 'x.^2';
yy = str2func(['@(',char(symvar(str)),')',str]);
use
x = 0:10;
out = yy(x);
ADD
str = 'x^2 - y^2'
k = strcat(symvar(str),',');
k = [k{:}];
yy = str2func(['@(',k(1:end-1),')',vectorize(str)]);
use
x = 1:10;
y = linspace(5,20,10);
out = yy(x,y);
  1 件のコメント
Andrei Bobrov
Andrei Bobrov 2013 年 3 月 7 日
added

サインインしてコメントする。


Walter Roberson
Walter Roberson 2013 年 3 月 7 日
f = str2func( ['@(x) ' TheString] );
yy = f(x);

カテゴリ

Help Center および File ExchangeShifting and Sorting Matrices についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by