Trying to integrate an problem with no analytic solution, can't figure out why my function file isn't working

6 views (last 30 days)
My limits of integration are a changing variable
This is my function file xint.m:
function fuxc = xint(T)
k = 1.38e-23;
e = 1.6e-19;
range = 50:0.01:y(T);
ex = exp(-e./(k.*range))
fuxc = trapz(range,ex);
end
function yrange = y(T)
yrange = T;
end
If i call xint for an arbitrary value of T it works i.e. xint(200) = 2.2224e-25
But if I want it to solve an array of T values i.e. T=200:1:300, xint(T):
I still get a single value of 2.2224e-25 instead of 101 different values...
I've been struggling with this all day and feeling like an idiot for not getting it to work, please help!

Answers (1)

Walter Roberson
Walter Roberson on 28 Feb 2013
When T is a vector, your y(T) returns the vector, and then your
range = 50:0.01:y(T);
would be attempting to start at 50, step by 1/100, with an endpoint that is a vector. That is not going to generate some kind of odd matrix that has 50:0.01:T(1) in one row, 50:0.01:T(2) in another row, and so on. Instead it is going to warn you and it is going to be the same as 50:0.01:T(1) . Which would be the same as if you had only passed in a single value instead of a vector.
If you want to process a number of different values, you will need to loop over them, or else find some way of optimizing. Hint: cumtrapz and max(T)
  3 Comments
Walter Roberson
Walter Roberson on 28 Feb 2013
Why are you using a numeric approximation? Why not just integrate once with a symbolic upper bound, and then use the resulting formula?
a = 50;
b = T;
fucx = -exp(-e*(a+b)/(b*k*a))*(-e*(Ei(1, e/(a*k))-Ei(1, e/(b*k)))*exp(e*(a+b)/(b*k*a))+k*(exp(e/(b*k))*a-exp(e/(a*k))*b))/k;
You will need to convert the expression into vectorized form, and you will need to convert Ei to the appropriate MATLAB routine name. And for clarity I would recommend against mixing a variable named "e" in an expression that uses exp(), as it is too easy for humans to read "e" as meaning the base of the natural logs, exp(1)
Matt J
Matt J on 28 Feb 2013
Edited: Matt J on 28 Feb 2013
It gets really messy when I put a loop in my function file.
I don't see how. Since your function already works for scalar T, it should just be a matter of enclosing what you have already in a for-loop. In what way is the following "messy" than what you had originally, other than the few extra lines bracketing your original code?
function fuxc = xint(T)
k = 1.38e-23;
e = 1.6e-19;
N=length(T);
fuxc=zeros(1,N);
for i=1:N
range = 50:0.01:y(T(i));
ex = exp(-e./(k.*range))
fuxc(i) = trapz(range,ex);
end
end

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!