Having some problems with recursive function

1 vue (au cours des 30 derniers jours)
David Joseph
David Joseph le 5 Avr 2019
Commenté : David Joseph le 6 Avr 2019
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.

Réponse acceptée

Dennis
Dennis le 5 Avr 2019
Modifié(e) : Dennis le 5 Avr 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 commentaires
Guillaume
Guillaume le 5 Avr 2019
Modifié(e) : Guillaume le 5 Avr 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.
David Joseph
David Joseph le 6 Avr 2019
Wow. Thanks alot ! I get it

Connectez-vous pour commenter.

Plus de réponses (0)

Community Treasure Hunt

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

Start Hunting!

Translated by