How to run this matlab code?

655 Views Asked by At

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

There are 1 best solutions below

4
On BEST ANSWER

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