MATLAB: Lsqnonlin with matrices Problem to define the function

anonymous function with matrices for lsqnonlinlsqnonlinMATLABnonlinear-least square problemOptimization Toolbox

Hi Guys,
I am a bit new to topic of optimization, and I need some help with a nonlinear-least square problem.
I have a time vector t and the value for the function at each time t .
Knowing h can be approximated by:
For the matrices:
A=[0 0 0 -a1
1 0 0 -a2
0 1 0 -a3
0 0 1 -a4];
B=[b1;b2;b3;b4];
C=[0 0 0 1];
where the unknowns are a1, a2, a3, a4, b1, b2, b3, b4.
I tried to used the function lsqnonlin
fun = @(a1,a2,a3,a4,b1,b2,b3,b4) h - (C*expm([0 0 0 -a1;1 0 0 -a2;0 1 0 -a3; 0 0 1 -a4]*t)*[b1;b2;b3;b4]);
x0 = [1 1 1 1 1 1 1 1];
x = lsqnonlin(fun,x0)
But I am getting some errors:
Not enough input arguments.
Error in
h_test>@(a1,a2,a3,a4,b1,b2,b3,b4)h-(C*expm([0,0,0,-a1;1,0,0,-a2;0,1,0,-a3;0,0,1,-a4]*t)*[b1;b2;b3;b4])
Error in lsqnonlin (line 206)
initVals.F = feval(funfcn{3},xCurrent,varargin{:});
Error in h_test (line 35)
x = lsqnonlin(fun,x0)
Caused by:
Failure in initial objective function evaluation. LSQNONLIN cannot
continue.
Now
  1. It looks like there are some problems with the anonymous function fun.
  2. I still have some doubts about the correct way to built the anonymous function, specially in the argument of the exponential function: expm(A*t), becuse here I have a matrix A times a vector t, however matrix A have to by multiplied by the time corresponding to the value of h. Let's say that in a for loop it should be something like: h(k) – (C*expm(A* t(k))*B), but I have no idea how that could be implemented in anonymous functions.
Any help are welcome,
Thanks in advance!

Best Answer

As clearly stated in the documentation, "...an objective function ... accepts one input, say x." One input, not a1,a2,a3,a4,b1,b2,b3,b4.
You need to map x to a1,a2,a3,a4,b1,b2,b3,b4. So take x(1) = a1, x(2) = a2, x(3) = a3, x(4) = a4, x(5) = b1, x(6) = b2, x(7) = b3, and x(8) = b4. Then your function becomes (assuming h, C, and t are already in your workspace)
fun = @(x) h - (C*expm([0 0 0 -x(1);1 0 0 -x(2);0 1 0 -x(3); 0 0 1 -x(4)]*t)*[x(5);x(6);x(7);x(8)]);
Alan Weiss
MATLAB mathematical toolbox documentation
Related Question