Search code examples
matlabintegral

Best way to integrate user defined function


I would like to evaluate an expression which requires an integral of a user defined function.
I have 3 inputs to the integral expression, E,F and B. F and B are values stored in separate arrays. E is the parameter I would like to integrate over, from a value of 0 to the value of B. I am trying to use the integral function with a user defined function, although I keep getting a matrix dimension error, which I do not comprehend as all the values for F, B (I thought) are being passed as scalar inputs.

However, I realize that for each iteration of the loop I am defining a new function, this seems "inelegant". Any advice as to 1. Why it will not run as is (i.e. the error using *, inner matrix dimensions must agree) 2. Any more elegant solution?

Here is the loop

     for i=1:51
               % DEFINE energy integrand, without prefixes
               nrgInt=@(E,F,B) sqrt(E)*exp(-8*pi*(m*q)^(0.5)*(B-E)/(3*h*F))/(exp(E/(k*Temp))+1);
    % Integrate over energy range, store           
               J(i)=q*mu*8*pi*sqrt(2)*m.^1.5/h^3*Farray(1,i)*integral(@(E)nrgInt(E,Farray(1,i),Barray(i)),0,Barray(i));
               clear nrgInt
        end

Much appreciated


Solution

  • For your 1st question, because * in Matlab represents matrix operator, so if not both sides of the operation are scalar, then both must have appropriate size, i.e m-by-n matrix * n-by-p matrix

    For 2nd question, you can define the function seperately, then use vertorizing instead of for-loop:

    J=q*mu*8*pi*sqrt(2)*m.^1.5/h^3*Farray(1,:)*integral(@(E)nrgInt(E,Farray(1,:),Barray(:)),0,Barray(:));