MATLAB: Finding the max value of a function containing an integral

integralmax value

I have been trying to find the value of "v" for the max value of "fun2". So my question is, how should I do this?
clear all;
close all;
clc;
k = 1.38e-23;
q = 1.60e-19;
h = 6.626e-34;
c = 3e+8;
R = 0;
T = 300;
Emin = 1.34;
x=0;
E = 8;
G = 2.187e+21;
% counter = 1;
% vstep = 0;
% Jstep = 0;
% Nstep = 0;
%P = 0;
%J = 0.01;
v = 0;
Eqmin= Emin*q;
Eq = E*q;
Const = (2*pi)/(h^3*c^2);
fun = @ (x) exp((q*v-x)./(k*T)).*x.^2;
fun2 = @(v) v*q(G-Const*(integral(fun,Eqmin,Eq)));
v0 = [0];
[v,fval] = fmincon(fun2,v0,[],[],[],[],[],[],[],[])

Best Answer

The problem is that ‘fun’ is a function of both ‘x’ and ‘v’. You have it only as a funciton of ‘x’. Changing that (and since you want the maximum, optimizing on the negative of ‘fun2’, and are not constraining the optimization so use fminunc) gives you the result you want:
fun = @ (x,v) exp((q*v-x)./(k*T)).*x.^2;
fun2 = @(v) v*q*(G-Const*(integral(@(x)fun(x,v),Eqmin,Eq)));
v0 = [0];
[v,fval] = fminunc(@(v)-fun2(v),v0)
v =
0.9867
fval =
-336.4596
Then negate ‘fval’ to get the actual value at the optimum, 336.4596.