Having some problems with recursive function
1 view (last 30 days)
Show older comments
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.
0 Comments
Accepted Answer
Dennis
on 5 Apr 2019
Edited: Dennis
on 5 Apr 2019
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 Comments
Guillaume
on 5 Apr 2019
Edited: Guillaume
on 5 Apr 2019
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.
More Answers (0)
See Also
Categories
Find more on Whos in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!