Search code examples
arraysmatlabintegral

Produce integration array as a function of integration limit in MATLAB


I'm trying to use the function integral to return an array of integrated points

I have a function defined:

v = @(t) cos(t);

and I'd like to find the integrated function, x(t) for several such values stored in tvec:

tvec = linspace(0,10,1000);    
x = @(tf) integral(@(t) v(t),0,tf,'ArrayValued',true);

But it doesn't appear that Matlab allows the array valued bit to be the limit of integration, since x(tvec) results in error. Any suggestions?


Solution

  • Note: there is a duplicate question with a much more efficient solution than this one.

    The problem is that integral only accepts scalar limits. In your example the integrand is scalar-valued, so you should omit the 'ArrayValued' setting: that will allow MATLAB to vectorize the integration for each upper bound.

    You can use arrayfun to feed each upper limit to integrate. Also, you can just pass v, a function handle to integral, no need to redefine an anonymous function for it locally:

    v = @(t) cos(t);
    x = @(tf) arrayfun(@(tmax) integral(v,0,tmax),tf);
    
    tvec = linspace(0,10,1000);    
    sinvec = x(tvec);
    

    It seems to work:

    figure;
    plot(tvec,sin(tvec),'s-',tvec,sinvec,'o-');
    legend('sin(tvec)','sinvec')
    

    result