Passing built fun tion to fminunc

1 次查看(过去 30 天)
I have built a function based on an input:
for r = 1:n
f = f - log(x(r)-x(r+n)) - log(finalconstraints(r,1)-x(r)) - log(x(r+n)-finalconstraints(r,2));
end
The function I get in f at the end is correct.
I am trying to pass that function to fminunc. I know that I must send a handler, so I did the following
fun = matlabFunction(f);
x0 = [2.4; -1.8; 1.6; -1.8];
[xf, ff] = fminunc(fun,x0);
I get the error 'Not enough input arguments'.
I cannot just have the form
fun = @(x)...
because the initial size of the matrix is unknown and function f depends on that. Therefore, I cannot skip the part where the function is built.
Any help is appreciate
  3 个评论
Arjun Rajan
Arjun Rajan 2019-12-1
I used a 2x2 just to test, the x0 matricx will be of unknown size later on as well
Walter Roberson
Walter Roberson 2019-12-1
The symbolic toolbox cannot be used to create functions in varying number of variables. In most (but not all) cases the symbolic toolbox can be used to create vectorized formulas, with the size of the output being the same as the size of the input.

请先登录,再进行评论。

回答(1 个)

Matt J
Matt J 2019-12-1
[xf, ff] = fminunc( @(x) fun( x(1),x(2),(3),x(4) ),x0);
  5 个评论
Arjun Rajan
Arjun Rajan 2019-12-1
The size will indeed be 2*n. However, n is the number of columns of the input matrix A, which is of unknown size. I have formulated my function f based on the input using the loop, but it is not possible to know n before hand. Is it still possible to send such a function to fminunc? or is it like Walter Roberson, and it cannot be dond?
Walter Roberson
Walter Roberson 2019-12-2
Is finalconstraints a function? Is it a 2D matrix? Which is your symbolic variable that you will later minimize over?

请先登录,再进行评论。

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by