Why is this code not working whilst the other is?

조회 수: 1 (최근 30일)
Michael Vaughan
Michael Vaughan 2020년 9월 24일
댓글: Steven Lord 2020년 9월 24일
I have written this script:
function sum = Sum2(x,y,z)
s = 0;
for i=0:min(x,y)
for k=0:y-i
s = s + (-1)^k * QuantumDimension(2*x+k-2*i, 2*y-2*k-2*i) * Twist(2*x+k-2*i, 2*y-2*k-2*i)^(z/2);
end
end
s
When I type Sum2(5,3,2) it gives me an appropriate output
but then I have the script
function sum = Sum3(x,y,z)
s = 0;
for i=0:min(x,y)
s = s + (-1)^k * QuantumDimension(2*x-2*i, 2*y-2*i) * Twist(2*x-2*i,2*y-2*i)^(z/2);
end
end
s
And when I type Sum3(5,2,1) I get:
Error: File: Sum3.m Line: 8 Column: 1
This statement is not inside any function.
(It follows the END that terminates the definition of the function "Sum3".)
What the heck?!?!? The placement of s in the script is completly similar to the function Sum2... What is going on here!! Thanks

채택된 답변

Ameer Hamza
Ameer Hamza 2020년 9월 24일
편집: Ameer Hamza 2020년 9월 24일
You have written an 's' after end of the function. Nothing should come after the end keyword
function sum = Sum3(x,y,z)
s = 0;
for i=0:min(x,y)
s = s + (-1)^k * QuantumDimension(2*x-2*i, 2*y-2*i) * Twist(2*x-2*i,2*y-2*i)^(z/2);
end
end
s % remove this
Also note that 'k' is not defined.
In the case of Sum2, you don't have an end keyword corresponding to the function. Remember the end keyword is optional. The two end keyword you have are related to for loops.
  댓글 수: 1
Steven Lord
Steven Lord 2020년 9월 24일
More to the point, it looks like Sum3 is a copy of Sum2 but with (almost) all references to k edited away. If that's the case Michael Vaughan erased the for k = ... line from the copy but forgot to erase the corresponding end statement (rather than typing s after the second end.)
If you make this copy by copying and pasting in the MATLAB Editor you'll receive one red Code Analyzer error and two orange Code Analyzer warnings in the copy. The second of those warnings states that for is not aligned with its corresponding end, which may lead the developer to take a closer look at their end statements.
The first Code Analyzer warning is due to the fact that these functions are defined to return a variable named sum (which should not be used as a variable name as it already has a meaning in MATLAB) but the functions never define that variable.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Startup and Shutdown에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by