1

I got code that I can't run that is said to produce the result:

z = [0:500:4000 5000:1000:12000];
data = [5050 4980 4930 4890 4870 4865 4860 4860 4865 ...
        4875 4885 4905 4920 4935 4950 4970 4990];
fun = @(p)(4800 + p(1))*ones(size(z)) +p(2)/1000*z+p(3)*exp(p(4)/1000*z)-data;
x0 = [0 0 0 -1]; % Guess
opt = optimoptions('lsqnonlin', 'MaxFunEvals', 1000);
p = lsqnonlin(fun,x0,[],[],opt)
fitf = @(t)(4800 + p(1))*ones(size(t)) + p(2)/1000*t+ p(3)*exp(p(4)/1000*t);
tt = linspace(0,12000,1000);
plot(z,data,'r-',tt,fitf(tt),'b-');

It's something with the comment % Guess that makes it that I can't run it directly and neither can I change the code to make it runnable. What is it suppesed to be?

The background is this question: How to fit non-linear matlab data?

1 Answers1

5

The character % marks a comment in Matlab, so everything after that on the same line is ignored by the interpreter. Also, I believe the function optimoptions you were using does not exist, the correct should be optimset. Maybe this is what you wanted:

z=[0:500:4000 5000:1000:12000];
data=[5050 4980 4930 4890 4870 4865 4860 4860 4865 4875 4885 4905 4920 4935 4950 4970 4990];
fun=@(p)(4800 + p(1))*ones(size(z)) +p(2)/1000*z+p(3)*exp(p(4)/1000*z)-data;
x0=[0 0 0 -1];
opt = optimset('MaxFunEvals',1000);
p=lsqnonlin(fun,x0,[],[],opt);
fitf=@(t)(4800 + p(1))*ones(size(t)) + p(2)/1000*t+ p(3)*exp(p(4)/1000*t);
tt=linspace(0,12000,1000);
plot(z,data,'r-',tt,fitf(tt),'b-');

After running the code above you should get the figure below. Graphic output

Dimas
  • 562
  • 3
  • 12
  • 1
    optimoptions certainly does exist and is documented here. It's possible that it's only available in newer versions? – horchler Aug 13 '13 at 15:37
  • 1
    @horchler optimoptions exists only in the optimization toolbox, whereas optimset is available without that toolbox. – Emily Aug 13 '13 at 16:05
  • 1
    @Arkamis: Good point. lsqnonlin is itself in the Optimization Toolbox, so if you can run that, then optimoptions should be available. Or just use opts = struct('MaxFunEvals',1000);. – horchler Aug 13 '13 at 16:09
  • 1
    In my version of matlab optimoptions was not available, but it is not the latest version, so I guess the code I suggested is more backwards-compatible. – Dimas Aug 13 '13 at 19:12