MATLAB: What is wrong with line 13

unused variable

xl = -2; %Lower limit
xu = 1; %Upper limit
es = 100;
imax = 100;
while (ea>=es) && (iter < imax)
R = (sqrt(5)-1)/2; %Golden Ratio value
d = R*(xu - xl);
x1 = xl + d; %Initial guesses to determine the bounds
x2 = xu - d;
iter = 1;
ea = es +1;
f(x1) = f1;
f(x2) = f2;
if f(x1) > f(x2)
xl = x2;
x2 = x1;
xopt = x1;
fmax = f(x1);
x1 = xl + d;
f2 = f1;
else
xopt = x2;
x1 = x2;
d = R + d;
x2 = xu - d;
f(x1) = f(x2);
end
if xopt ~=0
ea = (1 - R)*abs(xint/xopt)*100;
end
if (ea>=es) && (iter < imax)
xint = xu - xl;
iter = iter + 1;
else
break
end
end
disp (['The maximum is located at ', num2str(xopt), ' and ', num2str(fopt)]);
function [y] = f(x)
y = -(x^4) - (2*x^3) - (8*x^2) - (5*x);
end

Best Answer

You have
xl = -2; %Lower limit
then you do not change x1 before you do
f(x1) = f1;
so you are trying to do
f(-2) = f1;
which attempts to assign the result of the function f1 to the third location before the start of storage of f. That is not permitted: arrays can only be indexed with positive integers.
Ah, actually I just noticed that this is f(x1) rather than f(xl) . I did not calculate exactly what x1 is, but I can see at a glance that it will obviously not be a positive integer.
Your code never assigns to f1 but it does assign to f2, which might leave some people with the impression that you intended f1 to be a variable but forgot to initialize it, rather than a function with no parameters which you forgot to post the code for.
You have a function named f . If you manage to get through either of the assignments
f(x1) = f1;
f(x2) = f2;
then afterwards f would no longer refer to the function and would instead refer to the array of results that you are constructing.
You appear to be trying to use f2 before you assign to it. Or perhaps you have a function named f2 whose code you did not post and you have a conflict between that function and using f2 as a variable.
I get the impression that you are trying to define formulae -- trying to define that f(x1) should return a particular value, and that f(x2) should return a different particular value. You cannot do that in MATLAB. The symbolic toolbox does permit one to do things like
syms t
f(t) = sin(t).^2 / 10
to define a formula for f, but the symbolic toolbox does not permit defining special cases by individual assignment: if you had the above lines and were then to try
f(-1) = 7;
then that would be an error, an attempt to index at a negative value; and if you had used
f(1) = 7;
then that would overwrite f's identity as a function. If you want to define special cases for a function, they have to be coded into the function itself. http://www.mathworks.com/help/matlab/math/parameterizing-functions.html can help for that.
Related Question