Having some problems with recursive function

2 Ansichten (letzte 30 Tage)
David Joseph
David Joseph am 5 Apr. 2019
Kommentiert: David Joseph am 6 Apr. 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.

Akzeptierte Antwort

Dennis
Dennis am 5 Apr. 2019
Bearbeitet: Dennis am 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 Kommentare
Guillaume
Guillaume am 5 Apr. 2019
Bearbeitet: Guillaume am 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 am 6 Apr. 2019
Wow. Thanks alot ! I get it

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Matrices and Arrays finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by