how to create symbolic function for vector input?

2 ビュー (過去 30 日間)
Jiayan Yang
Jiayan Yang 2018 年 12 月 21 日
コメント済み: Walter Roberson 2018 年 12 月 22 日
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

採用された回答

Walter Roberson
Walter Roberson 2018 年 12 月 21 日
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 件のコメント
Walter Roberson
Walter Roberson 2018 年 12 月 22 日
編集済み: Walter Roberson 2018 年 12 月 22 日
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
Walter Roberson 2018 年 12 月 22 日
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.

サインインしてコメントする。

その他の回答 (0 件)

Community Treasure Hunt

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

Start Hunting!

Translated by