Search code examples
matlabfor-loopfactorial

Basic structure of a for loop


I am trying to write a MATLAB function that accepts non-integer, n, and then returns the factorial of it, n!. I am supposed to use a for loop. I tried with

"for n >= 0"

but this did not work. Is there a way how I can fix this?

I wrote this code over here but this doesn't give me the correct answer..

    function fact = fac(n);
    for fact = n
        if n >=0
            factorial(n)
            disp(n)
        elseif n < 0
            disp('Cannot take negative integers')
        break
        end
    end

Any kind of help will be highly appreciated.


Solution

  • You need to read the docs and I would highly recommend doing a basic tutorial. The docs state

    for index = values
        statements
    end
    

    So your first idea of for n >= 0 is completely wrong because a for doesn't allow for the >. That would be the way you would write a while loop.

    Your next idea of for fact = n does fit the pattern of for index = values, however, your values is a single number, n, and so this loop will only have one single iteration which is obviously not what you want.

    If you wanted to loop from 1 to n you need to create a vector, (i.e. the values from the docs) that contains all the numbers from 1 to n. In MATLAB you can do this easily like this: values = 1:n. Now you can call for fact = values and you will iterate all the way from 1 to n. However, it is very strange practice to use this intermediary variable values, I was just using it to illustrate what the docs are talking about. The correct standard syntax is

    for fact = 1:n
    

    Now, for a factorial (although technically you'll get the same thing), it is clearer to actually loop from n down to 1. So we can do that by declaring a step size of -1:

    for fact = n:-1:1
    

    So now we can find the factorial like so:

    function output = fac(n)
        output = n;
        for iter = n-1:-1:2 %// note there is really no need to go to 1 since multiplying by 1 doesn't change the value. Also start at n-1 since we initialized output to be n already
            output = output*iter;
        end
    end
    

    Calling the builtin factorial function inside your own function really defeats the purpose of this exercise. Lastly I see that you have added a little error check to make sure you don't get negative numbers, that is good however the check should not be inside the loop!

    function output = fac(n)
        if n < 0
            error('Input n must be greater than zero'); %// I use error rather than disp here as it gives clearer feedback to the user
        else if n == 0
            output = 1;  %// by definition
        else
            output = n;
            for iter = n-1:-1:2 
                output = output*iter;
            end
        end
    end