Search code examples
matlabfminsearch

Error in fminsearch (line 191) fv(:,1) = funfcn(x,varargin{:});


I want to minimize the below function which uses few constants(Hz,h,LR,k,T), but ending up with an error,....Please get me out of this.... I have loaded .rpt file which contains values as shown on top of code.......Thanks in advance.

3.25E+008   9.55E+002
3.03E+008   1.61E+005
2.77E+008   3.35E+005
2.54E+008   1.98E+006
1.17E+008   1.48E+003
1.13E+008   6.20E+004
1.00E+008   7.96E+005
9.15E+007   2.12E+003

format compact
format long

Hz = 3;
h = 3.99E-10;
LR = 0.1;
k = 8.3145;
T = 297.15;

load sdata_ndata.rpt
count = size(sdata_ndata,1);
xdata = zeros(count,1);% Stress
ydata = zeros(count,1);% Nf

for i=1:count

   xdata(i) = sdata_ndata(i,1);
   ydata(i) = sdata_ndata(i,2);

end

%Function to calculate the sum of residuals for a given p1 and p2
fun = @(p) sum((ydata-(((p(1)*(Hz*h*(1-LR))*xdata)*(exp((p(2))/(k*T))))/(((k*T)^2)*((exp((p(1)*xdata)/(k*T)))-(exp((p(1)*LR*xdata)/(k*T))))))).^2);

%starting guess
pguess = [1.338463e-003;1.234006e+005];

%optimise
[p,fminres] = fminsearch(fun,pguess)

Solution

  • The error lies in the definition of fun. There, the part

    ...(k*T))))/(((k*T)^2)...
    

    creates a matrix division which results in the (n,n) shape rather then the expected (n,1) shape. Therefore, the subtraction does not work any more. Replace the division by an element-wise division

    ...(k*T))))./(((k*T)^2)...