%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% rc.m
%
% MATLAB solution for Curve Fitting with Monte Carlo Method
%
% Problem: 
%               R
%       +------/\/\/-----+
%       |                |
% V0 -------            --- C
%      ---              ---
%       |                |
%       +----------------+
%
% The potential across the capacitor in a charging RC circuit 
% is given by:
%         Vc = V0(1-exp(-t/tau))
% where t is the time, V0 is the emf of the external battery and 
% tau = R*C is the time constant. An experiment is performed 
% to get the follwoing data:
%         t = [1.0 2.0 3.0  4.0];  % seconds
%         Vc= [4.7 7.5 9.3 10.4];  % volts
%         e = Vc*0.01;             % error on each Vc measurement
% 
% The aim is to find V0 and tau parameters via MC fitting method.
%
% July 2013
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

Smin = 1e+19;
t = [1.0 2.0 3.0  4.0];
Vc= [4.7 7.5 9.3 10.4];
e = Vc*0.01;

for k=1:250000
   % estimate range of the parameters
   tau = 0 + (10-0)*rand;
   V0  = 9 + (50-9)*rand;
   % compute the sum
   S = sum( ((Vc-V0*(1-exp(-t/tau))) ./ e ).^2 );
   % save the minimum
   if S<Smin
     Smin = S;
     taumin = tau;
     V0min = V0;
   end
end

fprintf('tau = %f  and V0 = %f\n',taumin, V0min)
