different answers for implementing summation

1 回表示 (過去 30 日間)
Terry McGinnis
Terry McGinnis 2015 年 6 月 22 日
編集済み: Terry McGinnis 2015 年 6 月 22 日
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 件のコメント
Terry McGinnis
Terry McGinnis 2015 年 6 月 22 日
編集済み: Terry McGinnis 2015 年 6 月 22 日
thanks.the vectorised code looks the most viable

サインインしてコメントする。

その他の回答 (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 Center および File ExchangeLogical についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by