different answers for implementing summation

1 次查看(过去 30 天)
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?

采纳的回答

Guillaume
Guillaume 2015-6-22
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 个)

Andrei Bobrov
Andrei Bobrov 2015-6-22
编辑:Andrei Bobrov 2015-6-22
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

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by