In my script, I call a function value to input values and put the input in another function integrnfn:
[A,x1,x2]=value;
y=integrfn(A,x1,x2);
fprintf('The value of the integral is %.3f', integrfn(A,x1,x2))
function [A,x1,x2]=value
A=input('Please enter a positive value: ');
x1=input('Please enter another positive value: ');
x2=input('Please enter a positive value that is greater than the previous one: ');
end
function y=integrfn(A,x1,x2)
y=int(A*exp(-x^2)*cos(2*x)/(1+x^2),x,x1,x2);
end
However, when I run it, it says:
Undefined function or variable 'x'.
Error in script >integrfn (line 15)
y=int(A*exp(-x^2)*cos(2*x)/(1+x^2),x,x1,x2);
Error in the script (line 5)
y=integrfn(A,x1,x2);
Can someone tell me the problem?
Thank you!!

 채택된 답변

Star Strider
Star Strider 2017년 11월 10일

0 개 추천

The int function is part of the Symbolic Math Toolbox. The most appropriate function is integral, with the integrand as an anonymous function:
y = integral(@(x) A*exp(-x.^2).*cos(2*x)./(1+x.^2),x1,x2);

댓글 수: 6

Zhuoying Lin
Zhuoying Lin 2017년 11월 12일
But it turns out that regardless of the input the output value is always o. Why?
Star Strider
Star Strider 2017년 11월 12일
That is not the result I get:
A = 5;
x1 = 1;
x2 = 10;
y=integral(@(x) A*exp(-x.^2).*cos(2*x)./(1+x.^2),x1,x2)
y =
-188.9829e-003
I do not see any errors in your code that would lead that a result always being 0.
Zhuoying Lin
Zhuoying Lin 2017년 11월 12일
The result is right only if I type the number and equation directly, yet if I run the whole script the result is always 0.
Star Strider
Star Strider 2017년 11월 12일
This code works for me:
function [A,x1,x2]=value
A=input('Please enter a positive value: ')
x1=input('Please enter another positive value: ')
x2=input('Please enter a positive value that is greater than the previous one: ')
end
function y=integrfn(A,x1,x2)
y = integral(@(x) A*exp(-x.^2).*cos(2*x)./(1+x.^2),x1,x2);
end
[A,x1,x2]=value
y=integrfn(A,x1,x2)
fprintf('The value of the integral is %.3f', integrfn(A,x1,x2))
When I run it:
Please enter a positive value: 10
A =
10.0000e+000
Please enter another positive value: 1
x1 =
1.0000e+000
Please enter a positive value that is greater than the previous one: 5
x2 =
5.0000e+000
A =
10.0000e+000
x1 =
1.0000e+000
x2 =
5.0000e+000
y =
-377.9658e-003
The value of the integral is -0.378
Zhuoying Lin
Zhuoying Lin 2017년 11월 12일
I figure out why now. Thank you!
Star Strider
Star Strider 2017년 11월 12일
My pleasure!

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

추가 답변 (0개)

카테고리

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

태그

질문:

2017년 11월 10일

댓글:

2017년 11월 12일

Community Treasure Hunt

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

Start Hunting!

Translated by