Passing a string to a function

2 ビュー (過去 30 日間)
Jared
Jared 2013 年 11 月 20 日
コメント済み: Sean de Wolski 2013 年 11 月 20 日
If I have a function:
function zp=F(x,z)
zp=zeros(2,1);
zp(1)=z(2);
zp(2)=a*sqrt(1+z(2)^2)+kx;
And I utilize it by:
[x,z]=ode45(@(x,z) F(x,z,a,kx),[x0,xf],[z10,z20]);
It works fine if I define a and kx equal to a number. However, in the case that a or kx may not equal a number, but another variable expression, I am not sure how to pass that. I tried kx='x^2', which doesn't work. But if I type x^2 in place of kx in the command line, it works. How can I set the kx equal to a variable epxression which can be passed to the function?

回答 (1 件)

Sean de Wolski
Sean de Wolski 2013 年 11 月 20 日
Just pass in x^2
[x,z]=ode45(@(x,z) F(x,z,a,x^2),[x0,xf],[z10,z20]);
It's throwing an error because inside of F you're trying to add a two element string. The anonymous function creation captures the workspace so you can have dynamic things (such as x^2) in it.
Also, your F function needs to take four inputs:
function zp=F(x,z,a,kx)
zp=zeros(2,1);
zp(1)=z(2);
zp(2)=a*sqrt(1+z(2)^2)+kx;
So that it can retrieve them from the anonymous function.
  2 件のコメント
Jared
Jared 2013 年 11 月 20 日
I got it to work as you state, by just putting in x^2. However, I have a bunch of different expressions, and I didn't want to have to call that whole expression each time, and instead, use a loop.
Sean de Wolski
Sean de Wolski 2013 年 11 月 20 日
Loop over the values calculated by the various expressions...

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

カテゴリ

Help Center および File ExchangeCharacters and Strings についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by