Matlab Int
Matlab Int
f (x) = x2 .
We can do this in (at least) three different ways. The shortest is:
>>int(’xˆ2’)
ans =
1/3*xˆ3
Alternatively, we can define x symbolically first, and then leave off the single quotes in the
int statement.
>>syms x
>>int(xˆ2)
ans =
1/3*xˆ3
Finally, we can first define f as an inline function, and then integrate the inline function.
>>syms x
>>f=inline(’xˆ2’)
f=
Inline function:
>>f(x) = xˆ2
>>int(f(x))
ans =
1/3*xˆ3
>>intoff=int(f(x))
intoff =
1/3*xˆ3
>>intoff=inline(char(intoff))
intoff =
Inline function:
intoff(x) = 1/3*xˆ3
1
The inline function intoff(x) has now been defined as the antiderivative of f (x) = x2 . △
The int command can also be used with limits of integration.
Example 2. Evaluate the integral
Z 2
x cos xdx.
1
In this case, we will only use the first method from Example 1, though the other two methods
will work as well. We have
>>int(’x*cos(x)’,1,2)
ans =
cos(2)+2*sin(2)-cos(1)-sin(1)
>>eval(ans)
ans =
0.0207
Notice that since MATLAB is working symbolically here the answer it gives is in terms of
the sine and cosine of 1 and 2 radians. In order to force MATLAB to evaluate this, we have
to use the eval command. △
For many functions, the antiderivative cannot be written down in a closed form (as the
sum of a finite number of terms), and so the int command cannot give a result. As an
example, the function
2
f (x) = e−x
falls into this category of functions. If we try int on this function, we get:
int(’exp(-xˆ2)’)
ans =
1/2*piˆ(1/2)*erf(x)
where by erf(x) MATLAB is referring to the function
2 Z x −y2
erf(x) := √ e dy,
π 0
which is to say, MATLAB hasn’t actually told us anything. In cases like this, we can proceed
by evaluating the integral numerically.
2
quad(’exp(-x.ˆ2)’,1,2)
ans =
0.1353
The quad command requires an input function that can be appropriately evaluated for vector
values of the argument, and so we have used an array operation. △
The quad command can also be used in order to evaluate functions defined in M-files. In
this way it’s possible to integrate functions that have no convenient closed form expression.
Example 4. Evaluate the integral Z 10
y(x)dx,
0
where y is implicitly defined by the relationship
x = y 3 + ey .
In this case, we cannot solve explicity for y as a function of x, and so we will write an
M-file that takes values of x as input and returns the associated values of y as output.
The for loop is necessary so that the function yfunction can be evaluated at vector values
for the independent variable x, as required by the quad command. We find
quad(@yfunction,0,10)
ans =
9.9943
(There is also an alternative approach to this type of problem that involves relating the
integral of y(x) to the integral of x(y), but that’s not the topic of this section.)
3 Assignments
1. Find an antiderivative for the function
f (x) = x sin2 x.
3
3. Evaluate the integral Z 2
sin(x2 )dx.
1
x = y + sin y.