2
votes

I can write in function in Matlab in this way:

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

We set the parameters, call the function:

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

This will return [6.0;6.0]. Does the option"[]" signal to fsolve that the input is a vector?

Anyway, how can I implement this in Julia using a NLsolve, Optim or JuMP? The original problem has more than 10 variables, so I would prefer a vector approach.

I can implement the function in Julia:

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

But simply using NLsolve:

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

Returns:

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

If I alternatively use Optim, I get:

using Optim
optimize(h!, a01)

which returns:

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.

Thank you for your suggestions!

1
Could you state what parts of e.g. the documentation of NLsolve you've looked at, and what in particular is causing you problems?Michael K. Borregaard
There is an update!pp11
Did you look at the NLsolve.jl documentation? That's not how you define the function. If your function is not in place, you use nlsolve(not_in_place(f), initial_x). But why not just use the inplace version from the documentation? function f!(x, fvec) first vector is input second is output?Chris Rackauckas
Thanks! not_in_place(f) would do it. I just needed to keep the odd definition of the function!pp11

1 Answers

3
votes

Following the suggestion by Chris Rackauckas, the solution would be to keep the definition of h:

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

and to use not_in_place:

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

Returning a solution:

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

Thank you!