Search code examples
matlabnumerical-integration

MATLAB offset when plotting integration of sin


I have a question, because this work for many functions, but I have a trouble when trying to plot the integral of a sine (I am using matlab 2010):

clear all
close all
clc

x = linspace(-10, 10, 100);

f = @(x) sin(x);

I = arrayfun(@(x) quad(f, 0, x), x);
plot(x, f(x),'r', x, I, 'b')

I expect having a -cos(x), but instead I get something with an offset of 1, why is this happening? How should fix this problem?


Solution

  • The Fundamental Theorem of Calculus says that the indefinite integral of a nice function f(x) is equal to the function's antiderivative F(x), which is unique up-to an additive constant. Further, a definite integral has the form:

    Fundamental Theorem of Calculus

    In this form, the constant of integration will cancel out, and the integral will exactly equal the desired antiderivative only if the lower bound evaluation vanishes. However, -cos(0) does not vanish and has a value of -1. So in order to calculate the desired antiderivative F(x), the lower bound evaluation should be added to the right-hand side.

    plot(x, f(x),'r', x, I+ (-cos(0)), 'b');
    

    This is the equivalent of assigning an initial value for the solution of ODEs a la ode45.