Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Problems integrating in a for loop in Matlab

  1. Dec 30, 2011 #1


    User Avatar
    Gold Member

    Problems integrating in a "for" loop in Matlab

    My problem strikes me as embarrassingly simple, so hopefully someone can set me straight with ease.

    I'm writing a Matlab code in which I'll be wanting to do a good amount of integrating of products of various eigenfunctions. Presently, I'm just trying to get the code up and running and can't seem to get a basic "for" loop to function as I'd expect.

    I'd expect that it would populate an array called "spatial" with seven elements, each of which is an integral of a cosine raised to a given power.

    Instead, it creates a singly-valued variable called "spatial" and then stops. For what it's worth, the value that it assigns is what I'd expect for the first execution of that loop.

    Here is the exact code giving me this grief:

    moments = 7;
    a = 11;
    lambda = pi/a;

    for C1 = 1,moments

    integrand = @(x)(cos(lambda*x).^(C1+1))
    spatial(C1) = quad(integrand,-a/2,a/2)


    Any help would be greatly appreciated.
    Thank you kindly.
  2. jcsd
  3. Jan 2, 2012 #2


    User Avatar
    Science Advisor
    Gold Member

    Re: Problems integrating in a "for" loop in Matlab

    Your syntax for 'for' isn't right - it should be:

    Code (Text):
    for C1 = 1:moments
    to do what you want. Writing it the way you did only executes the loop once (with C1 = 1).
  4. Jan 2, 2012 #3


    User Avatar
    Gold Member

    Re: Problems integrating in a "for" loop in Matlab

    Thank you kindly for taking the time to help me out. Member Joffan just pointed it out to me as well.

    Unbelievably simple mistake, and even more unbelievable failure to see it. Especially given that I've a dozen other functioning Matlab scripts with heavy use of for loops.

    Thanks again. Hopefully I'll be less ridiculous in the future.
Share this great discussion with others via Reddit, Google+, Twitter, or Facebook