These are 2 subprograms i have used to define 2 function grad and fnc. I have called the function grad , and in the function grad fnc is called, now x is a vector, and fnc is a scalar function of a vector variable still it is returning a vector
조회 수: 1 (최근 30일)
이전 댓글 표시
the second thing is that an error '??? Subscript indices must either be real positive integers or logicals' is coming... the error comes in the line 'grad1(k,1)=(fnc(x1)-fn(x))/(0.001)' of the grad func subprogram.
function N5=grad(fnc,x)
grad1=zeros(length(x),1);
x1=x;
for k=1:1:length(x)
x1(k,1)=x1(k,1)+0.001;
grad1(k,1)=(fnc(x1)-fn(x))/(0.001);
x1=x;
end
N5=grad1;
function N4= fnc(x)
N4=(x(1,1)*x(1,1)+x(2,1)-11.0)^2+(x(1,1)+x(2,1)*x(2,1)-7)^2;
댓글 수: 0
답변 (2개)
Marta Salas
2014년 3월 11일
The problem is that fnc is an input for grad, so fnc is a variable from now on. When you try to call fnc(x), MATLAB thinks you're trying to access position x on the array fnc and returns an error because x is not an integer.
I think what you want is:
function N5=grad(x)
grad1=zeros(length(x),1);
x1=x;
for k=1:length(x)
x1(k,1)=x1(k,1)+0.001;
grad1(k,1)=(fnc(x1)-fnc(x))/(0.001);
x1=x;
end
N5=grad1;
function N4 = fnc(x)
N4=(x(1,1)*x(1,1)+x(2,1)-11.0)^2+(x(1,1)+x(2,1)*x(2,1)-7)^2;
Walter Roberson
2014년 3월 11일
When you call grad() pass the function handle of fnc as the first argument
grad(@fnc, rand(1,50)) %for example
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Operators and Elementary Operations에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!