0
votes

I am trying to implement a recursive function to add the odd numbers in a vector v. So far this is my attempt

function result = sumOdd(v)
%sum of odd numbers in a vector v
%sumOdd(v)

n = 1;
odds = [];

if length(v) > 0
    if mod(v(n),2) == 1
        odds(n) = v(n);
        v(n) = [];
        n = n + 1;
        sumOdd(v)
    elseif mod(v(n),2) == 0
        v(n) = [];
        n = n + 1;
        sumOdd(v)
    end

else
    disp(sum(odds))
end
end

This does not work and returns a value of zero. I am new to programming and recursion and would like to know what I'm doing wrong.

Thank you.

2
Do you have to use recursion? There are much better ways to do this in matlab using logical indexing. - Daniel
You never assign anything to result and you never get what your recursive calls return. - Daniel
Yes, it has to be done via recursion. - John Connor

2 Answers

2
votes

There is a better way to solve this in MATLAB:

function result=summOdd(v)
    odd_numbers=v(mod(v,2)); % Use logical indexing to get all odd numbers
    result=sum(odd_numbers); % Summ all numbers.
end

To give a recursive solution:

When implementing a recursive function, there is a pattern you should always follow. First start with the trivial case, where the recursion stops. In this case, the sum of an empty list is 0:

function result = sumOdd(v)
%sum of odd numbers in a vector v
%sumOdd(v)


if length(v) == 0
    result=0;
else
    %TBD

end
end

I always start this way to avoid infinite recursions when trying my code. Where the %TBD is placed you have to put your actual recursion. In this case your idea was to process the first element and put all remaining into the recursion. First write a variable s which contains 0 if the first element is even and the first element itself when it is odd. This way you can calculate the result using result=s+sumOdd(v)

function result = sumOdd(v)
%sum of odd numbers in a vector v
%sumOdd(v)

if length(v) == 0
    result=0;
else
    if mod(v(1),2) == 1
        s=v(1);
    else
        s=0;
    end
    v(1) = [];
    result=s+sumOdd(v);
end
end

Now having your code finished, read the yellow warning the editor gives to you, it tells you to replace length(v) == 0 with isempty(v).

0
votes

Instead of keeping 'n', you can always delete the first element of v. Also, you need to pass 'odds' as an argument, as you're initializing it as an empty array at each time you call the function (hence the zero output).

The following example seems to do the job:

function result = sumOdd(v,odds)
%sum of odd numbers in a vector v
%sumOdd(v)

if ~isempty(v)
    if mod(v(1),2) == 1
        odds = [odds;v(1)];
        v(1) = [];
        sumOdd(v,odds)
    elseif mod(v(1),2) == 0
        v(1) = [];
        sumOdd(v,odds)
    end

else
    disp(sum(odds))
end
end