简体   繁体   中英

Anonymous function defined by a loop in matlab

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!

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM