different answers for implementing summation
1 vue (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Terry McGinnis
le 22 Juin 2015
Modifié(e) : Terry McGinnis
le 22 Juin 2015
im trying to implement summation in the following 2 ways:
1.
f1=[10 20 30 40 50]
x1=[1 2 3 4 5]
J=0
for i=1:5
J=J+((f1(i)-a*exp(-(x1(i)-mu)^2/sigma))^2)
end
and 2.
f1=[10 20 30 40 50]
x1=[1 2 3 4 5]
J=0
J=@(f,x) ((f-a*exp(-(x-mu)^2/sigma))^2)
for i=1:5
J(f1(i),x1(i))
end
and im getting different final answers for each.
can anyone tell why?
0 commentaires
Réponse acceptée
Guillaume
le 22 Juin 2015
Really, the best way of implementing your summation is option 3 which uses vectorised operations:
f1=[10 20 30 40 50]
x1=[1 2 3 4 5]
J = sum((f1 - a*exp(-(x1 - mu).^2 / sigma)) .^ 2)
Your option 2 looks like it wants to use J to store the result as in option 1 (since it has the line J = 0), but then put a function in J on the following line. In the loop you invoke the function but never assign the result to anything. I'm not sure what you expected to happen with that code. If you want to use an anonymous function, you could write your option 2 as:
func = @(f,x) (f-a*exp(-(x-mu)^2/sigma))^2;
J = 0;
for idx = 1 : numel(f1) %don't hardcode bounds, use numel to get the number of elements
J = J + func(f1(idx), x1(idx));
end
But again, vectorised code is better:
func = @(f,x) (f-a*exp(-(x-mu).^2/sigma)).^2; %note the use of .^ instead of ^
J = sum(func(f1, x1))
1 commentaire
Plus de réponses (1)
Andrei Bobrov
le 22 Juin 2015
Modifié(e) : Andrei Bobrov
le 22 Juin 2015
J = sum(f1-a*exp(-(x1-mu).^2/sigma)).^2)
for 2 variant:
f1=[10 20 30 40 50]
x1=[1 2 3 4 5]
J1=0
J=@(f,x) ((f-a*exp(-(x-mu)^2/sigma))^2)
for ii=1:5
J1 = J1 + J(f1(ii),x1(ii))
end
Voir également
Catégories
En savoir plus sur Logical 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!