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 vue (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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 commentaires
Réponses (2)
Marta Salas
le 11 Mar 2014
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
le 11 Mar 2014
When you call grad() pass the function handle of fnc as the first argument
grad(@fnc, rand(1,50)) %for example
0 commentaires
Voir également
Catégories
En savoir plus sur Debugging and Analysis dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!