Why quad function can't communicate with my subfunction?

16 vues (au cours des 30 derniers jours)
Amatriciana
Amatriciana le 9 Nov 2012
Hello, i have written two matlab functions to calculate the integral of functions which have a particular limit near zero.
first function:
function sinx
% This is the funtion file sinx.m
% Matlab functions quad and int are also used. The results are compared.
a=0; b=1; n=10;
S = simpson(@integrand, a, b, n);
Q = quad(@(x)integrand(x), a, b);
syms x;
E = double(int(sin(x)/x, x, a, b));
fprintf(' Simpson = %g\n Quad = %g\n Symbolic = %g\n ', S, Q, double(E))
function f = integrand(x)
if x>0
f=sin(x)./x;
else % If x-->0, f=1.
f=1;
end
second function:
function bessel
% This is the funtion file bessel.m
L=1; n=10;
nx=20; x=linspace(0,L,nx+1);
Q = zeros(nx+1,1);
for i=1:nx+1
a=x(1); xx=x(i); b=1-xx;
S(i) = simpson(@integrand, a,b,n,xx);
Q(i) = quad(@(t)integrand(t,xx), a ,b);
end
plot(x,Q,'k',x,S,'r');
legend('Quad','Simpson',0);
fprintf('e=%g\n', max(abs(Q-S))/max(abs(Q))*100)
function f=integrand(t,x)
z=sqrt((1-t).^2-x.^2);
if z>0
f=sin(t).*besselj(1,z).*x./z;
else
f=sin(t).*x/2; % besselj(1,z)/z -> .5 as z-> 0
end
Why in the first function (sinx.m) quad can't communicate with if/else, and matlab give me the error:
Error using quad (line 79) The integrand function must return an output vector of the same length as the input vector.
Thank you in advance for your help.

Réponses (1)

Matt Fig
Matt Fig le 9 Nov 2012
Modifié(e) : Matt Fig le 9 Nov 2012
If that is the error message, communication is not the problem. Re-read the message.... there is a problem with what your function returns.
Use this instead:
function f = integrand(x)
f = ones(size(x));
idx = x>0;
f(idx) = sin(x(idx))./x(idx);

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by