简体   繁体   中英

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

I think you misunderstood the line x = sym('x',[50 1]). It would create 50 symbolic variables starting from x1 to x50 within the workspace. But I think you need 1 variable x to be defined within the workspace and later you can use that x to create a function such that you may call that function passing a vector of size 50 to it to get the corresponding fx values.

If you want the function to be evaluated at all the values of x then you need to use the function subs(fx, x_points).

The sample code is given below.

    clc
    clear all

    m = 10;
    n = 10;
    A = rand(m,n);
    b = rand(m,1);
    c = rand(n,1);

    % declare the symbolic x variable
    syms x
    % declare the function
    f = symfun(c'* x - sum(log(A*x + b)), x);
    % declare the x data points
    x_points = ones(10,1);
    % substituting the x points within the f(x)
    evaluated_fx = subs(f, x_points)
% *********** perform the further operations below with the evaluated_fx

Please ensure that you use the dot(.) operator correctly while declaring a symbolic function otherwise you may get unexpected results with incorrect resulting dimensions.

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