MATLAB: 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

integralnumerical integrationsimpsons rule

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.

Best Answer

Actually, the integral of sin(x) is NOT -cos(x). This is a mistake that people frequently make. The integral is -cos(x), PLUS a constant of integration. That is, the indefiinite integral:
int(sin(x),x) == -cos(x) + C
Where C can be any constant number. Why is this important? Suppose you think of this as a differential equation:
df/dx = sin(x)
Now, you want to integrate that ordinary differential equation, over the interval [a,b] = [5,30]. Again, we will find the general solution as
f(x) = -cos(x) + C
However, then when you solve an ODE, you consider the initial conditions to resolve the constant. What is f(a)? In your code, you implicitly defined f(a) to be ZERO. So, implicitly, you resolved the constant C as:
C = cos(5)
C =
0.283662185463226
Now, given ths plot you created, I'll overlay the function -cos(x)+C.
plot(x,int);
hold on
xint = linspace(5,30,100);
plot(xint,-cos(xint) + C,'ro')
As you can see, the curve you generated (in blue) and the red dots I plotted overlay perfectly.
You need to remember that constant of integration, or it will hurt you when you are not looking. As far as your code having worked for you on other problems, well you may have just gotten lucky. Everything would look perfectly ok as a result of your code, IF it turned out that the initial condition of f(a)=0 just happened to have been correct. And then you ran into this problem, where that initial condition turned out to have been not what you expected.