% script file fminsearch_diode.m % % Sets arrays of measured data and uses fmins function % to find best values of reverse saturation current, Is, % and temperature, T, for a Shockley's Law diode model: % i = Is (exp(v/vT) - 1) where vT = kT/q is thermal voltage. % Declare global variables for measured data so they are % accessible inside tot_sq_err function. global v_diode global i_diode % Define physical constants. k = 1.38e-23; % J/degK Boltzmann constant q = 1.602e-19; % C electron charge % Create arrays containing measured data. v_diode = [1.3 1.35 1.4 1.41]; i_diode = [0.0006 0.0022 0.0136 0.0211]; % Find optimal Is and T by calling fmins function. % Matlab requires that Is and T be placed together in % one array. We call this array x: % x = [Is T] % We must specify initial values, which we call x0, where % fmins will start its search. % We use the linear regression solution as our starting guess. % (Note: if the initial guess is too far off, fmins may fail.) x0 = [2.5e-22 358.0]; % x0 = [Is T] % fmins returns the optimal array, x. % Note that we also must have a function called tot_sq_err % that fmins can call as tot_sq_err(x) with x as argument. % The name of the function is our choice, but we must tell % fmins what the name is. This function is defined in a file % named tot_sq_err.m, and we must set the path appropriately % (under FILE menu) so Matlab can find this file. % tot_sq_err must return a scalar value of the total model % squared error when the model parameters are given by x. x = fminsearch('tot_sq_err', x0); % We extract Is and T from x as the first and second entries. Is = x(1) T = x(2) % Done with the approximation. Now create a plot. % Calculate model predictions for the measured voltages. pred_i_diode = []; for ind = 1 : length(v_diode) p_i_diode = Is * (exp(v_diode(ind)/(k*T/q)) - 1); pred_i_diode = [pred_i_diode p_i_diode]; end % Print out predicted i values. pred_i_diode = pred_i_diode % Plot the measured and model values on the same plot. axes('FontSize',14) hold off plot(v_diode, i_diode, 'bo') hold on xlabel('LED voltage (V)','FontSize',14); ylabel('LED current (A)','FontSize',14); plot(v_diode, pred_i_diode, 'r-') legend('data','fminsearch fit','Location','Best'); hold off