Trying to integrate sinx using the integrate function but when I plot the integral, instead of plotting from -1 to 1 it plots from 0 to 2. Does anyone know why this happens?
Show older comments
I am using the "integrate" function to plot the integral of sin(x) [which is -cos(x)]. When I plot the integral it should plot from -1 to 1 but instead it is shifting the integral from 0 to 2. In the code below I show what I did. The @myFunInt is the following
function fval = myFunInt(x)
fval = sin(x);
end
and the main code is
clear
a=0; % lower limit
b=30; % upper limit
n=1000; % subintervals
h = (b-a)/n; % Spacing
x = 0:30;
int = zeros(1,n+1);
for j = 0:n
x_j=a+j*h; % x values are being allocated in the empty array
x(:,j+1)=x_j;
fun = @myFunInt;
y=integral(fun,a,x(:,j+1));
int(:,j+1)=y;
end
plot(x,int);
Note that this code works with any other function exept than integrading cos(x) and -sin(x).
Thank you for your input.
Accepted Answer
More Answers (1)
Geoff Hayes
on 3 May 2019
Guillermo - I'm guessing it is the y-axis limits that you want to be between -1 and 1? Why is the minimum value, a, fixed but the maximum is variable? Why the interval [5,30]? Is the units for this interval supposed to be radians, degrees, or does it not matter?
Note that if I use a and b as
a=0; % lower limit
b=2*pi; % upper limit
Then the figure is drawn as

which has the interval [0,2] which is what you describe. Is this expected? I think so because when you integrate like
y=integral(fun,a,x(:,j+1));
then y is the area under the curve...so on each iteration of your loop, you are calculating the area from 0 to something a little larger (a function of j and h). When x is pi, then the area will be two (since area from 0 to pi/2 is one).
5 Comments
Guillermo Naranjo
on 3 May 2019
Edited: Guillermo Naranjo
on 3 May 2019
Geoff Hayes
on 3 May 2019
Edited: Geoff Hayes
on 3 May 2019
Also, -cos(pi/2) is zero so the value in the plot you show technically does not represent the integral of sin(x).
Yes Guillermo, but on each iteration of your loop, you are calculating
y=integral(fun,a,x(:,j+1));
So isn't y the area under the curve from a to x(:,j+1)? And so on each iteration of your loop, you are calculating an area which increases from 0 to pi (using my interval) and then decreases from pi to 0. You are then plotting the area calculated on each iteration...you are not plotting the integral of sin(x).
Geoff Hayes
on 3 May 2019
However, if you try integrating cos(x) instead of sin(x), the limits in the y-axis will be from -1 to 1 as expected.
Correct but again you have calculated and are plotting areas under the curve, and for cos, these limits make sense given its curve.
Guillermo Naranjo
on 6 May 2019
Guillermo Naranjo
on 6 May 2019
Categories
Find more on Numerical Integration and Differential Equations in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!