What is wrong with line 13?
Show older comments
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
1 Comment
Guillaume
on 1 Mar 2018
Which line is line 13?
Why should there be anything wrong with line 13?. If it gives you an error message then at the very least give us the text of the error message (everything in red). If it doesn't do what you want then tell us what it does and what you wanted it to do.
Don't leave it to us to guess what your problem is. The likelyhood that you get an answer decreases the harder you make it to help you.
Accepted Answer
More Answers (2)
Please consider Guillaume's advice.
I dare to guess, that your "line 13" is
f(x1) = f1;
Here you could get the error message:
Subscript indices must either be real positive integers or logicals.
because x1 does not have an integer value in opposite to the demands for indices. Remember that an index means a certain element of a vector. But your x1 is -0.145898033750315 initially.
The next bold guess is, that you want to replace
f(x1) = f1;
f(x2) = f2;
if f(x1) > f(x2)
by
f1 = f(x1);
f2 = f(x2);
if f1 > f2
Now "f(x1)" is not an indexed variable anymore, but a function evaluation for the argument x1.
The line "f(x1) = f(x2);" needs a fix also, but here I'm not sure, what you might want.
It is very ugly to use x1 (one) and xl (lowercase L) in the same code. This is very hard to distinguish.
It is strange, that the initialization happens inside the loop:
x1 = xl + d; %Initial guesses to determine the bounds
x2 = xu - d;
iter = 1;
ea = es +1;
Surely this must occur before the while loop, otherwise e.g. iter is reset to 1 in each iteration.
I can see at least two things wrong with the code you've posted.
- ea and iter are not defined before you try to use them on the line while ea>=es && iter < imax
- f(x1) = f1 and similar lines are complete nonsense. You can't assign a value to a function. I have no idea what you are trying to do with these.
Categories
Find more on Graphics Performance in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!