【问题标题】:Using MATLAB integral with anonymous functions使用带有匿名函数的 MATLAB 积分
【发布时间】:2016-05-02 11:01:39
【问题描述】:

我正在尝试使用 MATLAB integral() 函数沿表示时变值的分段线性函数的单个参数进行积分。

我想在原函数的基础上定义一个匿名函数:

t1 = 1;
t2 = 2;
t3 = 4;
t4 = 5;

a0 = 1;
a1 = 2;

f = @(x) accel_profile(t1,t2,t3,t4,a0,a1,x);

这里是 accel_profile.m:

function value = accel_profile(t1,t2,t3,t4,a0,a1, t)

if t <= t1
    value = a0;
    return
elseif (t <= t2)
    value = ((t-t1)/(t2-t1)) * (a1-a0) + a0;
    return
elseif (t <= t3)
    value = a1;
    return
elseif (t <= t4)
    value = ((t-t3)/(t4-t3)) * (a0-a1) + a1;
    return
else
    value = a0;
    return
end

问题是当我执行以下脚本时:

t_list = 0:0.1:6;
q = zeros(1,length(t_list))
for i = 1:length(t_list)
    q(i) = integral(f,0,t_list(i));
end

plot(t_list, q)

我得到以下堆栈跟踪:

Error using integralCalc/finalInputChecks (line 515)
Output of the function must be the same size as the input. If FUN is an array-valued integrand, set
the 'ArrayValued' option to true.
Error in integralCalc/iterateScalarValued (line 315)
                finalInputChecks(x,fx);
Error in integralCalc/vadapt (line 132)
            [q,errbnd] = iterateScalarValued(u,tinterval,pathlen);
Error in integralCalc (line 75)
        [q,errbnd] = vadapt(@AtoBInvTransform,interval);
Error in integral (line 88)
Q = integralCalc(fun,a,b,opstruct); 
515             error(message('MATLAB:integral:FxNotSameSizeAsX'));

我在 Windows 7 上运行 MATLAB 2015b。

【问题讨论】:

    标签: matlab math


    【解决方案1】:

    问题是 integral 为您的函数使用矢量化参数,但您的函数不支持它。

    文档中的相关部分:

    对于标量值问题,函数 y = fun(x) 必须接受向量参数 x,并返回向量结果 y。这通常意味着 fun 必须使用数组运算符而不是矩阵运算符。例如,使用 .* (times) 而不是 * (mtimes)。如果将 'ArrayValued' 选项设置为 true,则 fun 必须接受一个标量并返回一个固定大小的数组。

    Reference

    这意味着integral 将使用f([1,2,3]) 之类的参数调用您的函数f,并期望一个带有[f(1),f(2),f(3)] 的列表

    通用技术to vectorize a piecewise defined function are explained in this question

    【讨论】:

    • Aww,打败我了:( 将'ArrayValued' 设置为 true 也应该有效:然后只使用标量参数调用该函数。然后你不需要向量化(但你应该; 那会更快)。
    • @AndrasDeak:我认为该选项应该用于返回向量的函数,但我没有在这里更简洁地使用它。我的matlab版本太旧了,不能有这个选项,如果真的解决了,请写一个答案。
    • 将 'ArrayValued' 设置为 'true' 成功了,谢谢!我读到了,并认为这仅适用于返回数组值的函数,所以我的错!
    • 确实,Daniel,它有效,我刚刚检查过。谢谢,但我认为没有必要仅仅因为这个而添加新的答案:) 出于完整性考虑,请随意将其添加到您自己的答案中。 Here's the result, btw意味着用于数组值函数,但在底层它只是避免使用向量值输入来加速。
    猜你喜欢
    • 2013-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-08
    • 1970-01-01
    • 2015-12-01
    • 2014-12-22
    • 1970-01-01
    相关资源
    最近更新 更多