I am new to Matlab. I would like to integrate a function. I try int() and integrate() but they all cause problems to me - not enough parameters or other different errors, I have tried many combinations with documentation. My current code is the following, I would like to be able to pass numbers p and q to res and obtain a numerical result:
syms x;
w = 1;
hbar = 1.054571800*10^(-34);
k = (w/(pi*hbar))^(1/4);
e = @(q) (w*q/hbar)^(1/2);
waveF = @(q) k*exp(-feval(e,q)*feval(e,q)*1/2.0)*1.0/1;
func = @(p,q) waveF(q-x/2)*waveF(q+x/2)*exp(1i*p*x/(hbar));
res = @(p,q) int(func(p,q), x = -Inf..Inf);
Currently " x = " is indicated as en error although it seems ok according to the documentation.
Thanks.
You are using anonymous functions in concert with the Symbolic Toolbox and have mistakenly used the MuPAD version of int
, which is actually generating the error, when you wanted the Symbolic int
.
While mixing anonymous functions with Symbolic calls is not illegal, I think you would be better served by sticking to one paradigm of computation at a time:
Purely Symbolic version using Symbolic functions:
syms x p q e(q) waveF(q) func(p,q) res(p,q);
w = sym(1);
hbar = sym('1.054571800E-34');
k = (w/(pi*hbar))^(1/4);
e(q) = sqrt(w*q/hbar);
waveF(q) = k*exp(-e(q)^2/2);
func(p,q) = waveF(q-x/2)*waveF(q+x/2)*exp(1i*p*x/(hbar));
res(p,q) = int(func(p,q),x,-Inf,Inf);
I wrapped the value of hbar
in quotes to force the use of the supplied value and not the nearest rational representation that would've been coerced during computation.
Purely numeric version using anonymous functions and the numeric integral
function:
w = 1;
hbar = 1.054571800E-34;
k = (w/(pi*hbar)).^(1/4);
e = @(q) sqrt(w*q/hbar);
waveF = @(q) k*exp(-e(q).^2/2);
func = @(p,q,x) waveF(q-x/2).*waveF(q+x/2).*exp(1i*p*x/hbar);
res = @(p,q) integral(@(x) func(p,q,x),-Inf,Inf);
Both of these version generate NaN
when res
is evaluated, but that's probably a shortcoming of the integrand. However, the functional forms and ideas behind the above scripts won't change with different integrands.