Why do I receive unexpected results when passing a string as the first argument to QUAD?

1 次查看(过去 30 天)
When I use the QUAD function to integrate the function "f(x) = a*x - b" from "x = 0" to "x = 1", I expect the result "F = -3". However, if I execute the command:
a = 2; b = 4;
x = quad('a*x-b', 0, 1, [], [], a, b);
I receive the value 0.

采纳的回答

MathWorks Support Team
When multiple variable are used while specifying a string expression, the QUAD function creates an inline object whose input arguments are the variables in the aphanumeric order returned by the SYMVAR function. For information about the order returned by the SYMVAR function, see the following solution:
For the example
x = quad('a*x-b',0,1,[],[],a,b);
the function that will be integrated by quad is of the form:
y=f(a, b, x)
rather than this form:
y=f(x,a,b)
Therefore, the function is integrated with respect to the first variable "a", rather than "x".
To avoid this confusion, pass the function to be integrated as an anonymous function:
a = 2; b = 4;
x = quad((@(x) a*x-b),0,1)
If you are using a version prior to MATLAB 7.0 (R14), you will need to create an inline function or function file with the independent variable as the first input argument.
Inline function:
f = inline('a*x - b', 'x', 'a', 'b');
a = 2; b = 4;
x=quad(f, 0, 1, [], [], a, b);
Function file:
a = 2;b = 4;
x=quad(@func, 0, 1, [], [], a, b);
where func.m is:
function f = func(x, a, b)
f = a*x - b;

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Function Creation 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by