2017-08-07 52 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