简体   繁体   English

Matlab-使用arrayfun评估嵌套匿名函数

[英]Matlab - Evaluating nested anonymous function with arrayfun

I want to evaluate an anonymous function in Matlab, which again consists of several anonymous functions. 我想在Matlab中评估一个匿名函数,该函数又由几个匿名函数组成。

Please excuse the somewhat chaotic labeling of the variables as this is a strongly simplified version of the original problem: 请原谅变量有些混乱,因为这是原始问题的简化版本:

C.B_MT = 2; C.T = 24; C.OM_MT = 1/24; C.P_WTmax = 2;
ub = 3;
ObjFcn = @(x) CostFcn1(x,C,ub);
x = 1:4;
fit = ObjFcn(x)

The function that ObjFcn calls is the following: ObjFcn调用的函数如下:

function F = CostFcn1(x,C,ub)
    F = f_t(x,C,ub) + OM_DG(C) + TCPD_BES(x,C);
    function ft = f_t(x,C,ub)
        N = cell(1,2);
        ft = x(2)*C.B_MT+ub;
        for i = 1:2
            N{i} = C.B_MT*x(i+2)+ub;
        end
        ft = ft(x) + sum(arrayfun(@(N_q) N_q{1}(x), N));
    end

    function om_dg = OM_DG(C)
        om_dg = C.T*C.OM_MT;
    end

    function tcpd = TCPD_BES(x,C)
        tcpd = x(1)*C.P_WTmax;
    end
end

When I run the code without the part of the for-loop and arrayfun , it works without a problems ( fit = 10 ). 当我运行不带for循环和arrayfun ,它可以正常工作( fit = 10 )。 With arrayfun , however, I get an error. 但是,使用arrayfun出现错误。 How can I change the code that arrayfun doesn't cause any problems? 如何更改arrayfun不会引起任何问题的代码?

The problem is with the part where you are trying to access ft(x) and N_q{1}(x) . 问题出在您尝试访问ft(x)N_q{1}(x) Replace these parts with ft and N_q{1} and you should be good to go. 将这些部分替换为ftN_q{1} ,您应该会做得很好。

Also, unless you need to do anything else in the three nested functions you have. 另外,除非您需要在三个嵌套函数中执行其他任何操作,否则您将无法使用。 you can get rid of these functions and just directly use the statements inside of them. 您可以摆脱这些功能,而直接使用其中的语句。 that will save you a lot of overhead. 这样可以节省很多开销。 Here I add the optimized code: 在这里,我添加了优化的代码:

function F = CostFcn1(x,C,ub)
    om_dg = C.T*C.OM_MT;
    tcpd = x(1)*C.P_WTmax;
    N = zeros(1,2);
    ft = x(2)*C.B_MT+ub;
    for i = 1:2
        N(i) = C.B_MT*x(i+2)+ub;
    end
    ft = ft + sum(N);
    F = ft + om_dg + tcpd;
end

This should work if your original code is similar (the variables used here have the same type as in your original code) to the one you have posted 如果您的原始代码与您发布的代码相似(此处使用的变量与原始代码的类型相同),则此方法应该有效

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM