Fzero with defined scalar parameters

4 ビュー (過去 30 日間)
Francesco
Francesco 2014 年 12 月 16 日
回答済み: Francesco 2014 年 12 月 16 日
Hello, I am approaching to MATLAB by myself, but I have a problem: I'm writing a script, that I will simplify as follow
k=0.1805;
n=4;
r_t=1.78e-3;
I=151;
d_r=0.06;
d=0.0009/d_r;
delt=10;
f=0.907; % Parameter that I want to set and change when needed
r_c=r_t*sqrt(f);
q_r=0.0072*((1+2/n)/((1+(4/n))^(3/10)))*(I^(7/5))/(r_t*sqrt(f))^(12/5)
y=k*delt/((q_r)*d_r*r_t*sqrt(f))
x=fzero('( exp(-(x^2)))/(x*sqrt(pi))+erf(x) -1-0.1805*10/((0.0072*((1+2/4)/((1+(4/4))^(3/10)))*(151^(7/5))/(1.78e-3*sqrt(0.907))^(12/5)*(0.06)*(1.78e-3)*sqrt(0.907)))',3)
Now the problem arises when I compute x: it is computed as the zero of exp(-(x^2)))/(x*sqrt(pi))+erf(x) -y , but I can't introduce "y" in the string of fzero, so I've inserted all the numerical expression. This is a big deal, because everytime I want to change "f" I have to find it in the string and change its value, while I would like to substitute it only once, when I define it. If I want to change any other parameter, the problem is still the same... I've read about fmin, function_handle etc etc, but I was not able to understand those tools, because by now I know very little about MATLAB. Could you kindly help me to solve this particular problem? Please, I beg you also to be detailed, because nothing is so obvious to me, now. Thanks a lot!

採用された回答

Matt J
Matt J 2014 年 12 月 16 日
編集済み: Matt J 2014 年 12 月 16 日
You should not be using strings to specify the function whose root you are trying to find. It's a deprecated syntax. You should be using anonymous functions
y=1;
fun=@(x) exp(-(x^2))/(x*sqrt(pi))+erf(x) -y;
x=fzero(fun,x0)
For other options, see also Passing Extra Parameters.

その他の回答 (2 件)

Thorsten
Thorsten 2014 年 12 月 16 日
If FUN is parameterized, you can use anonymous functions to capture the problem-dependent parameters. Suppose you want to solve the equation given in the function myfun, which is parameterized by its second argument c. Here myfun is an M-file function such as
function f = myfun(x,c)
f = cos(c*x);
To solve the equation for a specific value of c, first assign the value to c. Then create a one-argument anonymous function that captures that value of c and calls myfun with two arguments. Finally, pass this anonymous function to FZERO:
c = 2; % define parameter first
x = fzero(@(x) myfun(x,c),0.1)
In your case use y instead of c and define myfun as exp(-(x^2)))/(x*sqrt(pi))+erf(x)

Francesco
Francesco 2014 年 12 月 16 日
Thank you both, you help me to save a lot of time!

カテゴリ

Help Center および File ExchangeProgramming についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by