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);
and the main code is
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
fun = @myFunInt;
Note that this code works with any other function exept than integrading cos(x) and -sin(x).
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)
Now, given ths plot you created, I'll overlay the function -cos(x)+C.
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.
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
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).