Search code examples
matlabintegerfactorial

Why does Matlab factorial function perceives an integer as a non-integer?


I'm trying to build a function in Matlab which generates a Taylor series around 0 for sine and the user can insert x (the value for which the sine is approximated) and a maximum error. Thus I want the function to check the maximum error and from this maximum it generates the amount of elements in the Taylor series.

I get the following error:

Error using factorial (line 20)

N must be an array of real non-negative integers.

Error in maxError (line 19)

y(x) = y(x) + (-1)^(j) * x^(2j+1)/factorial(2j+1)

Below my code.

function [n] = maxError(x,e);
%Computes number of iterations needed for a given absolute error.

n=1;

while abs(x)^(n+1)/factorial(n+1) >= e
    n = n+1;
end


if mod(n,2) == 0
    n=n+1;
end

y=@(x) x;

j=1;
while j<n
    y(x) = y(x) + (-1)^(j) * x^(2j+1)/factorial(2j+1)
    j=j+1;
end

return

I think I get the error because the factorial function can only take up integers, but the way I see it, I am feeding it an integer. Since j=1; and then gets larger by one per iteration, I don't see how Matlab can perceive this as something else than a integer.

Any help is appreciated.


Solution

  • You are using j as an indexing variable, which is also the complex number in Matlab, and your are forgetting a * multiply.

    You can use j as a variable (not recommended!) but when you are putting a number in front of it, Matlab will stil interpret is as the complex number, and not as the variable.

    Adding the multiplication symbol will solve the issue, but using i and j as variables will give you these hard to debug errors. If you had used a, the error would have been easier to understand:

    >> a=10;
    >> 2a+1
     2a+1
      ↑
    Error: Invalid expression. Check for missing multiplication operator, missing or 
    unbalanced delimiters, or other syntax error. To construct matrices, use brackets
    instead of parentheses.