how to create symbolic function for vector input?

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

 Risposta accettata

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 Commenti

Jiayan Yang
Jiayan Yang il 21 Dic 2018
Modificato: Jiayan Yang il 21 Dic 2018
Thanks for your advice.It works when computing value in terms of point but fails to compute gradient says,
Error using sym/gradient
Too many input arguments.
It is really troublesome since the calculation such as gradient(f,x) or f(x) involves later.
I also tried this form f = @(x) c'* x - sum(log(A*x + b)); it is easier to calculate f(x) but it is hard to calculate the gradient at certain point.
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.
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.

Accedi per commentare.

Più risposte (0)

Community Treasure Hunt

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

Start Hunting!

Translated by