user1018331
user1018331

Reputation: 143

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

Upvotes: 0

Views: 383

Answers (2)

Sam Roberts
Sam Roberts

Reputation: 24127

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

Upvotes: 2

tdc
tdc

Reputation: 8597

Seems like you could define integrand with an extra parameter, so

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

but when I run it still gives an error:

??? Error using ==> power
Matrix dimensions must agree.

Error in ==> @(v,b)(v-a).^(p-1).*(b-v).^(q-1)

Error in ==> quad at 76
y = f(x, varargin{:});

Not exactly sure what you're trying to do though ...

Upvotes: 0

Related Questions