MATLAB: Creating a perfect number function

MATLABnumbersperfect

Hi. I am currently having a prob. I need to create a function that takes in the number(n) as argument and returns true if n is a perfect number. I am not allowed to use vectors and for loop for this question. I am stuck at this few codes:
function num = perfect(n)
i=1;
sum = 0;
while i <= n/2
if rem(n,i) == 0
else
i = i +1
end
sum = sum + i;
end
if n == sum
n = true
I am a beginner in Matlab and I require assistance. Any kind soul out there to help me? Thanks!

Best Answer

First and foremost, learn to use matlab's debugger. Step through your code, see how the variables change after each instruction, and check that the result was what you expected.
There is clearly a problem with your code. You have a while loop that essentially says:
while i is some value
if some condition
do nothing. Particularly, do not change i
else
change i
end
do something that does not change i
end
You can see that under some condition i never changes, so the loop will repeat infinitely. You need to fix that.
As per John's comment, don't use sum as a variable name, as you won't be able to use the sum function.
Also note that
if somecondition
else
do something
end
is better written as
if ~somecondition
do something
end