Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

math - Using MATLAB integral with anonymous functions

I'm trying to use the MATLAB integral() function to integrate along a single parameter of a piecewise linear function that represents a time-varying value.

I would like to define an anonymous function based on the original function:

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

a0 = 1;
a1 = 2;

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

and here is the 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

The problem is that when I exercise the following script:

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)

I get the following stack trace:

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'));

I'm running MATLAB 2015b on Windows 7.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The problem is integral uses vectorized arguments for your function, but your function does not support it.

The relevant part from the documentation:

For scalar-valued problems, the function y = fun(x) must accept a vector argument, x, and return a vector result, y. This generally means that fun must use array operators instead of matrix operators. For example, use .* (times) rather than * (mtimes). If you set the 'ArrayValued' option to true, then fun must accept a scalar and return an array of fixed size.

Reference

This means integral will call your function f with arguments like f([1,2,3]) and expects a list with [f(1),f(2),f(3)]

The general techniques to vectorize a piecewise defined function are explained in this question


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...