Numeircal integral with external function and external parameter

I would like to calculate an integral whereas the integrand is a separate external function. Consider as an example that I have in my main script:
N=5;
I = integral(fn,0,Inf,'RelTol',1e-8,'AbsTol',1e-13)
Where N is a parameter of the integrand that appears in the separate function named: fn.m that has the following form:
function FUN= fn(x)
FUN=@(x) (x.^N).*exp(-x).*sin(x)
end
But when I do this I see the following error:
Undefined function or variable 'N'.
How can I help Matlab take this external parameter into the integrand function?

 채택된 답변

madhan ravi
madhan ravi 2019년 1월 12일
편집: madhan ravi 2019년 1월 12일
EDITED
N = 5;
F = fn(x,N); % function call
I = integral(F,0,Inf,'RelTol',1e-8,'AbsTol',1e-13)
function FUN = fn(x,N) % function definition
FUN = @(x) (x.^N).*exp(-x).*sin(x);
end
Gives:
I =
-15.0000

댓글 수: 7

Thanks Madhan, I did this but now I get the error message:
"Too many input arguments"
madhan ravi
madhan ravi 2019년 1월 12일
편집: madhan ravi 2019년 1월 12일
See edited answer , if it's what you are looking for make sure to accept the answer else let know.
Now it works, thanks!
Hi Madhan,
now that the method works I need to use these integrals in an fsolve routine to determine some coefficients. Are you familiar with the fsolve? If yes here is my problem: I would like to solve e.g. 2 equations in terms of itegrals (see below) to obtain two coefficients x1 & x2. If I write the program like this
clc
clear all
format long g
x0=[0 0]
x=fsolve(@FF4,x0)
function f4=FF4(x)
f4(1)=integral(@(y) x(1)*y.^2+x(2)-2.3333,0,1)
f4(2)=integral(@(y) x(1)*sin(x(2)*y),0,pi)
end
It will work perfectly and gives me the factors x1=1 & x2=2.
Now if I try to define the integrals in separate functions just as you suggested previously (this time with two parameters: N from above is replaced by x1 & x2) again I will receive the error message
"Undefined function or variable 'y'."
The code now looks like this:
clc
clear all
format long g
x0=[0 0]
x=fsolve(@FF3,x0)
function f3=FF3(x)
f3(1)=integral(fint1(y,x(1),x(2)),0,1)-2.333
f3(2)=integral(fint2(y,x(1),x(2)),0,pi)
end
function FUN1= fint1(y,x1,x2)
FUN1=@(y) x1*y.^2+x2
end
function FUN2= fint2(y,x1,x2)
FUN2=@(y) x1*sin(x2*y)
end
What am I doing wrong?
function f3=FF3(x)
f3(1)=integral(fint1(x(1),x(2)),0,1)-2.333
f3(2)=integral(fint2(x(1),x(2)),0,pi)
end
function FUN1= fint1(x1,x2)
FUN1=@(y) x1*y.^2+x2
end
function FUN2= fint2(x1,x2)
FUN2=@(y) x1*sin(x2*y)
end
Saeid
Saeid 2019년 1월 13일
편집: Saeid 2019년 1월 13일
Thank you Walter!

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Numerical Integration and Differentiation에 대해 자세히 알아보기

질문:

2019년 1월 12일

편집:

2019년 1월 13일

Community Treasure Hunt

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

Start Hunting!

Translated by