fmincon 和其他优化函数不需要您将所有内容都写成表达式,它们也可以针对函数进行优化。
function E = criterion(r, C, C2)
e = C.*r + C2.*r.^2;
E = sum(e(:));
我不完全确定fmincon 所需的语法,但我猜它类似于E = f(theta),其中theta 是您要调整的参数向量,使E 最小。由于我没有明确描述您的问题,因此我假设您的参数是C 和C2(如果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);
你可以像其他情况一样构造一个匿名函数。