MATLAB: Getting factorials to work in the equation

fourier

Hello everyone,
I am having a problem with my code where I need to use a factorial due to the equation needing it in the denominator as I'm solving for a Fourier coefficient. I keep getting: Error using factorial (line 20) N must be an array of real non-negative integers.
Here is the code I'm using:
if true
clear all, close all, clc
format long
fc = 2E9 %center frequency
W0 = 1 %omega 0
Tao = 30E-3 %Tao
T = 0.1 %T
k = linspace(0, 10E12, 1000) %k
y = ((((-1).^k).*(k.*pi.*(fc+(k.*10)).*Tao).^2.*k)./factorial(2.*k+1))
x = sum(y)
Ck = W0*(Tao/T)*abs(x) %coefficient
figure(1)
plot(Ck,y)
% code
end
First of all I'm confused by the line 20 since there are not that many lines in my code, but I get this error right after "Error in PlottingFourierCoeff (line 8) y = ((((-1).^k).*(k.*pi.*(fc+(k.*10)).*Tao).^2.*k)./factorial(2.*k+1))" and that makes sense since that's where the factorial comes into play. My code may be a little rough because I started at at the end of the day yesterday and didn't get all the way through it since I knew I needed to figure out how to fix the factorial problem, but thank you for any help on this matter in advance!

Best Answer

There's no guarantee that all the values of 2*k+1 are integer values and the factorial function is only defined for integer value inputs. What, for example, should factorial(1.2345) return? [I know someone will suggest gamma, but there are other issues at work here.]
But even ignoring that, you have a much larger issue. Given the magnitude of the elements in k, only the first term in your expression for y matters. All of the rest are large enough that factorial overflows to Inf.
Do one or more of the following:
  1. only operate with the first element of k
  2. reduce the magnitude of the values in k. Anything over k = 18 results in factorial(k) being greater than flintmax; anything over k = 170 results in factorial(k) overflowing to Inf. [The factorial function grows VERY quickly.]
  3. change the units of your problem. For example if you're working with quantities whose units are meters, consider representing your quantities in terms of kilometers instead.