MATLAB: Undefined variable error in nested function

fminsearchnested functionundefined variable

I keep getting the error message "Undefined function or variable 'z'." when I run:
z = [0.388039 0.264102 0.185497 4.66E-02 2.58E-02 7.68E-03]; %Smoke 1
D = 10; %mg
V = 25;
t = [1.0 3.0 5.0 14.0 18.0 24.0];
k1 = [0 1];
[kv,kval]=fmin(k1,D,t,z);
which calls the function below:
function [kv,kval]=fmin(k1,D,t,z)
[kv,kval]=fminsearch(@fminfunc,k1);
function f = fminfunc(kv)
sum=0;
for j=1:6
sum = sum + z(j) - (D/kv(2))*exp(-kv(1)*t(j));
end
f = sum^2;
return
return
and I get this output:
Undefined function or variable 'z'.
Error in hw4c_1>fminfunc (line 22)
sum = sum + z(j) - (D/kv(2))*exp(-kv(1)*t(j));
I'm not sure why the variable is undefined when I've already passed in the variables to the function. Please help

Best Answer

Did you see that MLint shows a warning for the 2nd return command? This should catch your attraction in case of problems.
The solution is easy: Close the functions with an end, not with return:
function [kv,kval]=fmin(k1,D,t,z)
[kv,kval]=fminsearch(@fminfunc,k1);
function f = fminfunc(kv)
S = 0;
for j=1:6
S = S + z(j) - (D/kv(2))*exp(-kv(1)*t(j));
end
f = S ^ 2;
end
end
I've replaced "sum" by "S", because shadowing builtin function causes troubles frequently.
A simplification:
function f = fminfunc(kv)
f = sum(z - (D/kv(2)) * exp(-kv(1)*t)) ^ 2;
return