MATLAB Answers

Error: Error using dlfeval Value to differentiate must be a traced dlarray scalar.

17 views (last 30 days)
Chiao-Ling Cheng
Chiao-Ling Cheng on 10 Apr 2021 at 1:08
Answered: Walter Roberson on 10 Apr 2021 at 13:57
Hello, I am working on auto differentiation. But it came up with a error shown as title.
Error: Error using dlfeval Value to differentiate must be a traced dlarray scalar.
I am not sure why this doesn't work. The benchmark function is CEC2005 benchmark function.
x=bnd(1)+(bnd(2)-bnd(1)).*rand(1,dim); % it's just random assinged x, can also be replaced by [0,0]
x0 = dlarray(x); % wrap it with dlarray
[fval,g] = dlfeval(@modifiedBenchmark,x0);
function [f,grad] = modifiedBenchmark(x)
f = @(x)benchmark_func(x,1); % 1 here means that I use the first benchmark function
grad = dlgradient(f,x);
end
I also tried the sample code on the official website.
% Example code
x0 = dlarray([-1,2]);
[fval,gradval] = dlfeval(@rosenbrock,x0)
function [f,grad] = rosenbrock(x)
f = 100*(x(2) - x(1).^2).^2 + (1 - x(1)).^2;
grad = dlgradient(f,x);
end
And it works fine.
Can anyone show me what's going wrong?: (
Thank you!

Accepted Answer

Walter Roberson
Walter Roberson on 10 Apr 2021 at 13:57
Notice the example code has
f = 100*(x(2) - x(1).^2).^2 + (1 - x(1)).^2;
grad = dlgradient(f,x);
so it is receiving an x (that is dlarray object), computing something with it, getting out a dlarray object, and passing that dlarray object to dlgradient along with the original dlarray that was input.
Whereas your attempted code has
f = @(x)benchmark_func(x,1); % 1 here means that I use the first benchmark function
grad = dlgradient(f,x);
Which constructs an anonymous function and passes the anonymous function to dlgradient. But dlgradient does not accept function handles.
You would need something like
f = benchmark_func(x,1); % 1 here means that I use the first benchmark function
grad = dlgradient(f,x);

More Answers (0)

Community Treasure Hunt

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

Start Hunting!

Translated by