如何为矢量输入创建符号函数?

时间:2018-12-21 19:57:11

标签: matlab

我是Matlab的新手,我想知道如何将向量输入到符号函数中。该文档中说过用x = sym('x',[50 1])创建向量并将其用于生成目标函数f(x),但是如果我想在x = ones(50, 1),因为输入需要50个变量。

如何更改我的代码以实现该目标?

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

1 个答案:

答案 0 :(得分:0)

我认为您误解了x = sym('x',[50 1])行。它将在工作区中创建从x1到x50的50个符号变量。但是我认为您需要在工作空间中定义1个变量x,然后您可以使用该x来创建一个函数,以便可以调用该函数,将大小为50的向量传递给该函数以获得相应的fx值。

  

如果希望函数在所有x值上求值,则   您需要使用功能subs(fx,x_points)。

示例代码如下。

    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
  

请确保在使用时正确使用dot(。)运算符   声明符号函数,否则可能会得到意外的结果   结果尺寸不正确。

相关问题