Azzera filtri
Azzera filtri

Having some problems with recursive function

2 visualizzazioni (ultimi 30 giorni)
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.

Risposta accettata

Dennis
Dennis il 5 Apr 2019
Modificato: Dennis il 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 Commenti
Guillaume
Guillaume il 5 Apr 2019
Modificato: Guillaume il 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.
David Joseph
David Joseph il 6 Apr 2019
Wow. Thanks alot ! I get it

Accedi per commentare.

Più risposte (0)

Categorie

Scopri di più su Matrices and Arrays in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by