【问题标题】:Writing summation expression in MatlabMatlab中写求和表达式
【发布时间】:2012-02-05 06:00:11
【问题描述】:

如何在 Matlab 代码中编写涉及变量求和的表达式,然后如何最小化表达式? 前任。我需要最小化以下功能

E= \sum_{i,j}[C_{ij}(r_{ij}) + C2_{ij}(r_{ij})^2]

对于 i 和 j 不同的 r_{ij}s 的任何值,我需要最小化上述表达式。

我可以在 MATLAB 中使用 fmincon(),但我无法适当地编写表达式以将其作为 fmincon() 的输入。

谢谢。

【问题讨论】:

    标签: matlab expression minimize


    【解决方案1】:

    试试这个:

    E = sum(sum( C.*r + C2.*r.^2 ));
    

    其中CC2r 是相同形状的矩阵。

    【讨论】:

      【解决方案2】:

      fmincon 和其他优化函数不需要您将所有内容都写成表达式,它们也可以针对函数进行优化。

      function E = criterion(r, C, C2)
        e  = C.*r + C2.*r.^2;
        E  = sum(e(:));
      

      我不完全确定fmincon 所需的语法,但我猜它类似于E = f(theta),其中theta 是您要调整的参数向量,使E 最小。由于我没有明确描述您的问题,因此我假设您的参数是CC2(如果r 是您的参数,情况类似且更简单)。

      由于fmincon 使用向量来存储系数,我们需要一个函数来获取这样的向量并将其转换为上述criterion 函数所需的大小。

      function E = criterionRolledC(theta,r)
        assert(numel(theta)==2*numel(r), 'The size of theta has to be twice the size of r');
        [M N] = size(r);
        C  = theta(1:M*N);      
        C2 = theta(M*N+1:end);
        C  = reshape(C , M, N);
        C2 = reshape(C2, M, N);
      
        E = criterion(r,C,C2);
      

      这样,您可以创建一个轻松符合优化器接口的匿名函数:@(theta)(criterionRolledC(theta,rValues)) 将在您当前工作区中的变量 rValues 包含您的 r 值时执行。

      如果你想要完全相反,即你的参数是r,它更简单:

      function E = criterionRolledR(theta,C,C2)
        assert(numel(theta)==numel(C), 'The size of theta has to be the same size as C');
        assert(all(size(C)==size(C2)), 'C and C2 need to have the same size');
        [M N] = size(C);
        r = reshape(theta, M, N);
      
        E = criterion(r,C,C2);
      

      你可以像其他情况一样构造一个匿名函数。

      【讨论】:

        猜你喜欢
        • 2012-11-17
        • 2016-03-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-08-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多