2

Assume:

z = [0.4 0.5 0.75]'  
function y = myfunct(x)  
y = quad(@sin, 0, x)

I'd like to calculate the definite integral of sin(x) from 0 to 0.4, to 0.5, and 0.75, using:

myfunct(z)

However, Matlab returns:

??? Error using ==> quad at 70  
The limits of integration must be scalars.  

I'd be thankful for any constructive suggestions.

skip
  • 297
  • 1
  • 6
  • 16

2 Answers2

2

You can use the arrayfun function in recent versions of MATLAB:

z = [0.4 0.5 0.75]';
y = arrayfun(@(upperLim)(quad(@sin,0,upperLim)),z);
Egon
  • 4,757
  • 1
  • 23
  • 38
1

You can also use quadv to do this. BUT, instead of making a vector of integration limits, make an array valued function so that when you integrate each element, the range of integration will be 0 to 1.

To be more specific, you want to integrate sin(x) from x = 0 to z. This is the same as integrating sin(u z)*z from u = 0 to 1 (u-substitution). Make an array function

F = @(u) [sin( .4 * u) * .4, sin( .5 * u ) * .5, sin( .75 * u ) * .75 ];

Then do

quadv(F,0,1)
MarkV
  • 1,030
  • 7
  • 15
  • 1
    I guess your way might be a bit faster than mine. But I'd restructure it a bit since you are repeating some information (i.e. when you want to change 1 limit, you have to change 2 numbers, when you want to change the function, you have to change 3 identifiers). The following code is equivalent to yours: `lims = [0.4 0.5 0.75]'; F = @(u)(sin(u.*lims).*lims); quadv(F,0,1)` – Egon Oct 17 '11 at 06:38
  • agreed. that is a much cleaner way of doing it, and generalizes better. I guess I was trying to be too explicit. – MarkV Oct 19 '11 at 03:23
  • Thank you both for the helpful comments. – skip Oct 19 '11 at 16:36