about 'Attempted to access x(2); index out of bounds because numel(x)=1'

Hi, here is my script code, I just copy it here.
function files: f_1.m
function y=f_1(x)
y=1-[x(1)^2]/4-[x(2)^2]/4-sin(-2*x(1)-3*x(2))/2;
end
function files: optimise.m
function [X, y] = optimise(function_name, x_0, delta)
f=function_name; X=x_0; Xi=x_0; g=zeros(size(x_0)); k=0; [M,N]=size(x_0);
while feval(f,Xi)-feval(f,X)>=0.0001||k<1
j=1; X=Xi; y=feval(f,X); k=k+1;
while j<=N
X1(j)=X(j)+ 0.0001;
g(j)=[feval(f,X1)-feval(f,X)]/0.0001;
j=j+1;
Xi=X+delta*g;
end
end
*In the command window ,when I enter the inpus,the errors show below.
>> [X, y] = optimise('f_1', [0.5 -0.9], 0.25)
Attempted to access x(2); index out of bounds because numel(x)=1.
Error in f_1 (line 2)
y=1-[x(1)^2]/4-[x(2)^2]/4-sin(-2*x(1)-3*x(2))/2;
Error in optimise (line 7)
g(j)=[feval(f,X1)-feval(f,X)]/0.0001;
anyone who can help me?thanks:)

 Accepted Answer

In optimize() you do not initialize X1 before you do
X1(j)=X(j)+ 0.0001;
so when j is only 1, this creates only a single element for X1. You then try to pass that single-element X1 into the function.

More Answers (0)

Categories

Products

Community Treasure Hunt

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

Start Hunting!