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 CenterFile Exchange에서 Logical에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by