0

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)
vivek
  • 15
  • 7
  • looks like a problem in your `fun` function... but I can't reproduce your mistake because of don't know what is `xdata, ydata` (can't load sdata_ndata.rpt). Can you show all necessary data for calculation? – Mikhail_Sam Feb 04 '16 at 07:49
  • Your need to replace the matrix division `...(k*T))))/(((k*T)^2)...` by an element-wise division `...(k*T))))./(((k*T)^2)...`. – Nemesis Feb 04 '16 at 08:12
  • Thanks Mikhail.......The sdata_ndata.rpt file contains the data shown at the begining of the code. (sdata is in column of 3.25E+008. and ndata is in column of 9.55E+002 ) – vivek Feb 04 '16 at 08:12
  • BTW: You can write `xdata = sdata_ndata(:,1)` and `ydata = sdata_ndata(:,2)` to avoid the `for`-loop. – Nemesis Feb 04 '16 at 08:16
  • Yeah.....thanks Nemesis.....it worked like a charm... – vivek Feb 04 '16 at 08:20
  • A large number of your parentheses are superfluous and make it difficult to read your code (and easier to introduce bugs/typos). Read about [operator precedence](http://www.mathworks.com/help/matlab/matlab_prog/operator-precedence.html). – horchler Feb 04 '16 at 17:28

1 Answers1

1

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)...
Nemesis
  • 2,324
  • 13
  • 23