2017-08-07 49 views
1

我可以在功能写在Matlab这样:解方程的非线性系统,朱莉娅

function res=resid(theta,alpha,beta); 
RHS=[]; 
LHS=[]; 
RHS= theta-alpha; 
LHS= theta*beta; 
res = (LHS-RHS); 

我们设定的参数,调用函数:

alpha=0.3;beta=0.95; 
a01=[1.0;1.0]; 
th=fsolve('resid',a01,[],alpha,beta) 

这将返回6.0 ; 6.0]。选项“[]”是否表示输入是矢量?

无论如何,我如何使用NLsolve,Optim或JuMP在Julia中实现?原来的问题有超过10个变量,所以我宁愿使用矢量方法。

我可以实现在朱莉娅的功能:

h! =function (theta) 
RHS=[]; 
LHS=[]; 
RHS= theta-alpha; 
LHS= theta*beta; 
res= (LHS-RHS); 
return res; 
end 

但仅仅使用NLsolve:

a01 = [1.0;1.0]; 
res = nlsolve(h!,a01) 

返回:

MethodError: no method matching (::##17#18)(::Array{Float64,1}, ::Array{Float64,1}) 
Closest candidates are: 
    #17(::Any) at In[23]:3 

如果我选择使用的Optim,我得到:

using Optim 
optimize(h!, a01) 

返回:

MethodError: Cannot `convert` an object of type Array{Float64,1} to an object of type Float64 
This may have arisen from a call to the constructor Float64(...), 
since type constructors fall back to convert methods. 

谢谢您的建议!

+0

你能说出例如你看过的NLsolve的文档,以及特别是什么导致你的问题? –

+1

有更新! – pp11

+1

你看过NLsolve.jl文档吗?这不是你如何定义这个功能。如果你的函数不适用,你可以使用'nlsolve(not_in_place(f),initial_x)'。但为什么不直接使用文档中的inplace版本?函数f!(x,fvec)'第一个向量输入第二个输出? –

回答

1

继克里斯Rackauckas建议,解决办法是保持h的定义:

h =function (theta) 
RHS=[]; 
LHS=[]; 
RHS= theta-alpha; 
LHS= theta*beta; 
res= (LHS-RHS); 
return res; 
end 

,并使用not_in_place:

a01 = [1.0;1.0]; 
solve = nlsolve(not_in_place(h),a01) 

返回一个解决方案:

Results of Nonlinear Solver Algorithm 
* Algorithm: Trust-region with dogleg and autoscaling 
* Starting Point: [1.0,1.0] 
* Zero: [6.0,6.0] 
* Inf-norm of residuals: 0.000000 
* Iterations: 3 
* Convergence: true 
    * |x - x'| < 0.0e+00: false 
    * |f(x)| < 1.0e-08: true 
* Function Calls (f): 4 
* Jacobian Calls (df/dx): 4 

谢谢!

+1

作为惯例,如果函数不是变异函数,则不应该调用函数'h!'。请参阅[本文档中的文档](https://docs.julialang.org/en/latest/manual/style-guide/#Append-!-to-names-of-functions-that-modify-their-arguments- 1)。此外,您应该将此标记为解决方案,以便其他SO用户可以看到它已解决。 –

+0

好的!但是由于我自己写了一个答案,我将能够在48小时内对其进行标记。但我会做到这一点... – pp11