Reputation: 43
I use anonymous functions in my code. For example:
G = @(x) [norm(A*x-b);A'*(A*x-b)];
norm(Ax-b) is the objective function and A'*(Ax-b) the gradient. Then,
Algo( G,varagin );
etc
What I would like to do is to define f with a loop:
n = 9;
k = 2;
t = 1 - x.^k;
f = 0;
for i=1:n
f = f + x(i,1)*prod(t(1:i-1));
end
grad_f = zeros(n,1);
for i0=1:n
s = t;
s(i0) = [];
for i=i0+1:n
grad_f(i0) = grad_f(i0) + x(i)*prod(s(1:i0-1));
end
grad_f(i0) = -k*x(i0)^(k-1)*grad_f(i0);
grad_f(i0) = grad_f(i0) + prod(t(1:i0-1));
end
Then I would like to do something like:
" G = @(x) [f,grad_f] "
Thanks a lot for your help!
Upvotes: 1
Views: 328
Reputation: 43
Found the answer: create F(x) and GRAD_F(x) as functions in matlab computing f and grad_f respectively. Then:
G = @(x) [F(x);GRAD_F(x)];
Algo(G,varargin);
Upvotes: 1