【问题标题】:Can Matlab integral2 deal with a non-anonymous function?Matlab integral2 可以处理非匿名函数吗?
【发布时间】:2020-01-12 00:26:20
【问题描述】:

我有一个用户定义的函数

function[Rout2] = SSP2(a1,a2,b1,b2,pB)  
if a1/b1>a2/b2
   if pB<=a1-b1*a2/b2
      Rout2 = (a1-pB)/b1; 
   else
       if pB<=a1+a2
          Rout2 = (a1+a2-pB)/(b1+b2); 
       else
          Rout2 = 0;  
       end
   end
else
    if pB<=a2-b2*a1/b1
       Rout2 = (a2-pB)/b2;  
    else
        if pB<=a1+a2
           Rout2 = (a1+a2-pB)/(b1+b2);  
        else
           Rout2 = 0;   
        end
    end     
end
end

b1,b2,pB 都是参数。我想使用Matlab integral2 将这个功能集成到a1 in [0,t1] 和a2 in [0,t2] 上。我最初尝试过

integral2(SSP2,0,t1,0,t2)

但它不起作用。然后我想这可能是我传递了额外的参数。于是我做了如下修改

function[R] = NumericalIntegration(b1,b2,pB,t1,t2)
function[Rout2] = SSP2(a1,a2)  
if a1/b1>a2/b2
   if pB<=a1-b1*a2/b2
      Rout2 = (a1-pB)/b1; 
   else
       if pB<=a1+a2
          Rout2 = (a1+a2-pB)/(b1+b2); 
       else
          Rout2 = 0;  
       end
   end
else
    if pB<=a2-b2*a1/b1
       Rout2 = (a2-pB)/b2;  
    else
        if pB<=a1+a2
           Rout2 = (a1+a2-pB)/(b1+b2);  
        else
           Rout2 = 0;   
        end
    end     
end
end
R = integral2(@SSP2,0,t1,0,t2);
end

现在,在函数NumericalIntegration 内部,函数SSP2 可以访问参数b1,b2,pB。我认为它应该工作。但事实并非如此。当我在主程序中调用函数NumericalIntegration 时,它会生成错误“输入参数不足”。我想知道是因为Matlab integral2 只能与那些单行匿名函数一起使用吗?

【问题讨论】:

  • 叫它integral2(@SSP2,0,t1,0,t2)? IE。你缺少函数句柄吗?

标签: matlab integration anonymous-function


【解决方案1】:

这里的问题是您定义函数的方式。要使用内置函数进行双重积分,被积函数应正确矢量化。

一种方法是使用 for 循环重写您的函数,以处理 a1 和 a2 是维度为 [m,n] 的二维数组的情况。但是您可以使用 MATLAB 逐元素乘法和逻辑运算符将您的函数定义为:

function[Rout2] = SSP2(a1,a2,b1,b2,pB)
    Rout2 = 0*a1;

    Rout2 = Rout2 + ((a1-pB)/b1).*(a1/b1>a2/b2).*(pB<=a1-b1*a2/b2) + &
        ((a2-pB)/b2).*(a1/b1<=a2/b2).*(pB<=a2-b2*a1/b1);
end

然后创建匿名函数并调用为:

b1 = rand;
b2 = rand;
pB = rand;

fun = @(a1,a2) SSP2(a1,a2,b1,b2,pB);

t1 = rand;
t2 = rand;
I = integral2(fun,0,t1,0,t2)

只需相应地定义您的参数b1、b2 和pB 以及集成限制t1 和t2。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-04-02
    • 2020-07-29
    • 2014-12-27
    • 1970-01-01
    • 2011-12-29
    • 2014-04-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多