在循环中使用匿名函数

时间:2017-11-25 14:52:07

标签: matlab loops for-loop dynamic anonymous-function

我想编程使用动态编程来解决线性程序。

假设我的目标函数中有3个变量。然后我想一次考虑每个变量,并使用fminsearch或其他东西找到最佳值。

现在我的代码有三个不同的匿名函数来解决每个变量。我想在一个循环中这样做,以便它是有效的。如何在循环中使用匿名函数?

Func1 = @(x) 2*x(1) 
Func2 = @(y) 3*y(1)
Func3 = @(z) 4*z(1)

我想做类似的事情:

Func(i) = @(x(i)) k(i)*x(i)

示例:

max z = 3x1+5x2
s.t.
x1 <=4
2x2  <=12
3x1 + 2x2  <=18 
x1>=0
x2>=0

到目前为止我尝试了什么:

func1 = @(x) -3*x(1);
[x1,minZ] = fmincon(func1,x0,A,b,[],[],lb,ub,[],options)
func2 = @(x) -5*x(1)-3*x1; %substituting from previous solution for x1...
[x2,minZ] = fmincon(func2,x0,A2,b2,[],[],lb2,ub2,[],options)

1 个答案:

答案 0 :(得分:0)

x0 = 0;

fun_b2 = @(x) 18 - (3 * x);
fun_fm = '@(x)(-5*{x2})-(3*{x1})';
opts = optimset('Algorithm','active-set','TolFun',1e-6);

% 1st parameter of the row: A as column vector
% 2nd parameter of the row: B first value (the second one is evaluated into the for loop
% 3rd parameter of the row: a column vector containing the upper and lower bounds
params = {
    [1 3] 4 [0 Inf];
    [2 2] 12 [0 3]
};
params_size = size(params,1);

res = NaN(params_size,1);

for i = 1:params_size
    % take the function in string form and replace the current parameter placeholder with x(i)
    fun = fun_fm;
    fun = strrep(fun,['{x' num2str(i) '}'],'x(1)');

    % replace the previous parameter placeholders with the known values
    for j = 1:i
        fun = strrep(fun,['{x' num2str(j) '}'],num2str(res(j)));
    end

    % replace the next parameter placeholders with 0
    if (i < params_size)
        for j = (i+1):params_size
            fun = strrep(fun,['{x' num2str(j) '}'],'0');
        end
    end

    % transform the string into a function handle
    fun = str2func(fun);

    % transpose the first parameter (A) to row vector
    A = params{i,1}.';

    % take the first B value and calculate the second one with the function
    b1 = params{i,2};
    b2 = fun_b2(x1);

    bounds = params{i,3};

    [xi,min_z] = fmincon(fun,x0,A,[b1 b2],[],[],bounds(1),bounds(2),[],opts);

    res(i) = xi;
end