how to create symbolic function for vector input?
2 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Jiayan Yang
el 21 de Dic. de 2018
Comentada: Walter Roberson
el 22 de Dic. de 2018
I'm new to Matlab and I wonder how to input a vector to a symbolic function. It is said in the document that creating vectors by x = sym('x',[50 1]) and use it for generate objective function f(x), but it doesn't work if I want to test the value of function when x = ones(50,1) since the input expects 50 variables.
How can I change my code to achieve that?
m = 100;
n = 50;
A = rand(m,n);
b = rand(m,1);
c = rand(n,1);
% initialize objective function
syms x
f = symfun([c'* x - sum(log(A*x + b))],x);
tolerance = 1e-6
% Max iterations
N =1000;
% start point
xstart = ones(n,1)
% Method: gradient descent
% store step history
xg = zeros(n,N);
% initial point
xg(:,1) = xstart;
fprintf('Starting gradient descent.')';
for k = 1:(N-1)
d = - gradient(f,xg(:,k));
if norm(d) < tolearance
xg = xg(:,1:k);
break;
end
0 comentarios
Respuesta aceptada
Walter Roberson
el 21 de Dic. de 2018
Symbolic functions cannot handle vectors of inputs as separate variables. For symbolic functions, input vectors or arrays are always treated as requests to vectorize the calculation.
Work-around:
x = sym('x',[50 1]);
f = c'* x - sum(log(A*x + b));
then
xc = num2cell(xg(:,k));
d = - gradient(f, xc{:});
3 comentarios
Walter Roberson
el 22 de Dic. de 2018
Editada: Walter Roberson
el 22 de Dic. de 2018
If you want to evaluate the gradient at a particular point, then
fg = gradient(f, x);
g = matlabFunction(fg, 'vars', {x});
after which
d = -g(xg(:,k));
There is a variation of this but it is only worth doing if you are going to be testing the gradient of a lot of points:
g = matlabFunction(fg, 'vars', {x}, 'file', 'fgrad.m', 'optimize', true);
I will update with relative timings when I have them.
Walter Roberson
el 22 de Dic. de 2018
47 seconds to creat the unoptimized MATLAB Function (not stored on disk, so would only persist between seconds if save/load)
0.0149 seconds to execute the non-optimized MATLAB version
705 seconds to create the optimized MATLAB function (stored on disk, so would persist between sessions)
0.000115 seconds to execute the optimized MATLAB function.
Improvement ratio: about 129
But to make up the extra 658 seconds of optimizing, you would need to be calling the function close to 6 million times. Not impossible, certainly.
Más respuestas (0)
Ver también
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!