Azzera filtri
Azzera filtri

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

1 visualizzazione (ultimi 30 giorni)
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.

Risposta accettata

MathWorks Support Team
MathWorks Support Team il 22 Gen 2010
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;

Più risposte (0)

Categorie

Scopri di più su Function Creation in Help Center e File Exchange

Prodotti

Community Treasure Hunt

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

Start Hunting!

Translated by