different answers for implementing summation

1 visualizzazione (ultimi 30 giorni)
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?

Risposta accettata

Guillaume
Guillaume il 22 Giu 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 Commento
Terry McGinnis
Terry McGinnis il 22 Giu 2015
Modificato: Terry McGinnis il 22 Giu 2015
thanks.the vectorised code looks the most viable

Accedi per commentare.

Più risposte (1)

Andrei Bobrov
Andrei Bobrov il 22 Giu 2015
Modificato: Andrei Bobrov il 22 Giu 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

Community Treasure Hunt

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

Start Hunting!

Translated by