Index exceeds the number of array elements (1)

function [tg] = TO(x0, eps)
obj = @(x) 7*x(1)^5 + 20*x(2)^5 + x(1)^3 + 12*x(2)^3;
gradient = @(x)[35*x(1)^4 + 3*x(1)^2; 100*x(2)^4 + 36*x(2)^2];
hessiana = @(x)[140*x(1)^3 + 6*x(1) 0;0 400*x(2)^3 + 72*x(2)];
x = x0;
tg = x0;
while(norm(gradient(x))>eps)
grad = gradient(x);
obj_alfa = @(alfa)obj(x - alfa*grad);
alfa_star = fminbnd(obj_alfa, 0, 1);
x = x - alfa_star*grad;
tg = [tg x];
end
x = x0;
tn = x0;
while(norm(gradient(x))>eps)
grad = gradient(x);
hess = hessiana(x);
d_newton = inv(hess)*grad;
obj_alfa = @(alfa) obj(x - alfa*d_newton);
alfa_star = fminbnd(obj_alfa, 0, 1);
x = x - alfa_star*d_newton;
tn = [tn x];
end
It gives the error in the subject line every time I try to call the function and I don't see why.

2 Comments

eps is a built-in function. Don't call your variable that. Call it eps1 or something. Now, how did you call it? For example did you do
x0 = rand(1, 500);
eps1 = .003;
tg = TO(x0, eps1)
or what??? You didn't just click the green run triangle without specifying x0 and eps1 did you?
Thank you for your fast answer!
I changed it to eps1 but it's the same.
I write in the command line:
x0 = 0;
eps1 = 0.1;
tg = TO(x0, eps1);
And here comes the error...

Sign in to comment.

 Accepted Answer

In the same vein as eps, don't use gradient as a name as it's already a matlab function. Note that using the names eps or gradient is not an error but it increases the chances of bugs later on (because you try to use the built-in function and forgot that you've shadowed it with your own variable).
I don't understand why you can't spot the problem which is obvious. The obj, gradient and hessiana functions that you've written all expect a 2 element input, yet you tell us yourself that the x (= x0) has only one element.

2 Comments

I took the programme as it is from a laboratory where it worked like this. On my computer it does not work. So I don't understand how it could have worked written exactly like this on another computer, but not on mine.
How do you say I can change it?Capture.PNG
Again, the problem is not with the code it's with the way you call it. The code expects an input with at least 2 elements (since it accesses x(2)).
The input you pass to the program has only one element, x0 = 0.

Sign in to comment.

More Answers (0)

Categories

Find more on Linear Algebra in Help Center and File Exchange

Tags

Asked:

on 12 Jan 2019

Commented:

on 12 Jan 2019

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!