How to use lsqnonlin with class method functions?
2 views (last 30 days)
Show older comments
I defined my method (method1) as a function file and stored it in a class folder. the method is functional and I don't have any problems using it.
I created another method and within it I want to use x = lsqnonlin(fun,x0,lb,ub) to evaluate method1.
Q =lsqnonlin(@method1, x0,lb,ub). I kept getting an error message:
Undefined function 'method1' for input arguments of type
'double'.
the only way to overcome this error was to copy the method function and paste it into the current path even though it's already defined in the class folder.
after doing that the code was able to locate the function but now I had another issue, inside the method1 function I used dot notation often to get property values for calculations and I think it's not supported for functions in lsqnonlin. this is the error message I get:
Dot indexing is not supported for variables of this type.
Error in method1 (line 21)
ndof=S.ndof;
Error in lsqnonlin (line 206)
initVals.F =
feval(funfcn{3},xCurrent,varargin{:});
Caused by:
Failure in initial objective function evaluation.
LSQNONLIN cannot continue.
0 Comments
Answers (1)
Steven Lord
on 6 May 2020
Yes.
I defined my method (method1) as a function file and stored it in a class folder. the method is functional and I don't have any problems using it.
Is it defined as a method of that class, or is it simply a function file inside that class's folder? There's a difference for classes defined in classdef files.
I created another method and within it I want to use x = lsqnonlin(fun,x0,lb,ub) to evaluate method1.
Q =lsqnonlin(@method1, x0,lb,ub). I kept getting an error message:
That's correct. lsqnonlin will call your function with a double precision input, not an instance of your class. If your method is not a Static method, at least one of the inputs must be an instance of the class for MATLAB to even consider calling the class method.
If the method is not Static, you probably want something like:
obj = anInstanceOfTheClassWithMethod1AsAMethod;
Q = lsqnonlin(@(x) method1(obj, x), x0, lb, ub)
This will call the method1 method for the class anInstanceOfTheClassWithMethod1AsAMethod and pass both the object and a double precision array into that method.
If the method is a Static method, you need to call it using the class name.
Q = lsqnonlin(@(x) anInstanceOfTheClassWithMethod1AsAMethod.method1(x), x0, lb, ub) % or
Q = lsqnonlin(@anInstanceOfTheClassWithMethod1AsAMethod.method1, x0, lb, ub)
0 Comments
See Also
Categories
Find more on Function Creation in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!