Search code examples
matlabnumericintegral

matlab quadrature in a loop


I'm trying to use matlab numerical integral functions,for example quad in a loop. But I also want to let matlab to calculate my integral for several integral limits:

p=1;
q=3;
for k=1:5
    a=0;
    b(k)=k.*10;
     integrand(k)=@(v)(v-a).^(p-1).*(b(k)-v).^(q-1);
p(k)=quad(integrand,a,b(k));
end

It really seems me clever:) but Matlab has no Idea:( Thank you for any help! mg


Solution

  • I think the main problem you have is that you're using p both as a parameter and also to store the results of your integration. So within the loop p becomes a vector, and then it can't be used as a power in the integrand. I'm not sure why, but I also seem to need to remove k as an index into b and integrand. But this code seems to work:

    p=1;
    q=3;
    for k=1:5
        a=0;
        b=k.*10;
        integrand=@(v)((v-a).^(p-1).*(b-v).^(q-1));
        result(k)=quad(integrand,a,b);
    end