title: Integration via trapezoidal sums in MATLAB
body: <p>I need help finding an integral of a function using trapezoidal sums.</p>
  
  <p>The program should take successive trapezoidal sums with <code>n = 1, 2, 3, ...</code>
  subintervals until there are two neighouring values of <code>n</code> that differ by less than a given tolerance. I want at least one <code>FOR</code> loop within a <code>WHILE</code> loop and I don't want to use the trapz function. The program takes four inputs:</p>
  
  <ul>
  <li><code>f</code>: A function handle for a function of <code>x</code>.</li>
  <li><code>a</code>: A real number.</li>
  <li><code>b</code>: A real number larger than <code>a</code>.</li>
  <li><code>tolerance</code>: A real number that is positive and very small</li>
  </ul>
  
  <p>The problem I have is trying to implement the formula for trapezoidal sums which is
  <code>Δx/2[y0 + 2y1 + 2y2 + … + 2yn-1 + yn]</code></p>
  
  <p>Here is my code, and the area I'm stuck in is the "sum" part within the <code>FOR</code> loop. I'm trying to sum up <code>2y2 + 2y3....2yn-1</code> since I already accounted for <code>2y1</code>.  I get an answer, but it isn't as accurate as it should be. For example, I get <code>6.071717974723753</code> instead of <code>6.101605982576467</code>.</p>
  
  <p>Thanks for any help!</p>
  
  <pre><code>function t=trapintegral(f,a,b,tol)
  format compact; format long;
  syms x;
  oldtrap = ((b-a)/2)*(f(a)+f(b));
  n = 2;
  h = (b-a)/n;
  newtrap = (h/2)*(f(a)+(2*f(a+h))+f(b));
  while (abs(newtrap-oldtrap)&gt;=tol)
      oldtrap = newtrap;
      for i=[3:n]
          dx = (b-a)/n;
          trapezoidsum = (dx/2)*(f(x) + (2*sum(f(a+(3:n-1))))+f(b));
          newtrap = trapezoidsum;
      end
  end
  t = newtrap;
  end
  </code></pre>