Having some problems with recursive function

1 次查看(过去 30 天)
function S = mySum(A)
S = plus(A, length(A))
function total = plus(arr, leng)
if(leng == 0)
total = 0
else
total = arr(leng) + plus(arr,leng - 1)
end
The above codes is used for computing the sum of the elements in an array. The problem here is that the function always returns "total = 0".
However, the function returns the correct value if i change
total = arr(leng) + plus(arr,leng - 1)
to
total = arr(leng) () plus(arr,leng - 1)
After debugging the script several times i realized some strange behaviours at "total". After plus(arr, 0) return 'total = 0'.
It will be total = arr(1) + 0, so this should be the sum of arr(1) and '0'. However, this calls plus(arr(1), 0).
Therefore, when i change :
if(leng == 0)
total = 50
Again, 'total = arr(leng) + plus(arr, leng - 1)' calls function plus(arr(leng), plus(arr, leng - 1)).
Here, 'total = arr(1) + plus(arr, 0)' calls function plus(arr(1), 50).
Can someone please explain whether 'total = arr(leng) + plus(arr,leng - 1)' calls (arr(leng), plus(arr, leng - 1)) or not and also the solution in this case.
Thanks a lot for your contribution.

采纳的回答

Dennis
Dennis 2019-4-5
编辑:Dennis 2019-4-5
This strange behaviour originates in a unfortunate function name.
function S = mySum(A)
S = myplus(A, length(A))
function total = myplus(arr, leng)
if(leng == 0)
total = 0
else
total = arr(leng) + myplus(arr,leng - 1)
end
  2 个评论
Guillaume
Guillaume 2019-4-5
编辑:Guillaume 2019-4-5
This strange behaviour originates in a unfortunate function name.
To clarify that, plus is the functional name of the + operator. By naming your function plus you effectively changed the way addition worked.
Similar function names to avoid, minus, times, sum, mean, etc.
Didn't you get a warning when you saved your file:
Warning: Function plus has the same name as a MATLAB builtin. We suggest you rename the function to avoid a potential name conflict.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Matrices and Arrays 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by