MATLAB: Numerical integration of function to determine Fourier coefficients

arraycell arraysfourierfunction handlesintegrate

Hello,
Looking for an efficient and succinct way to numerically calculate N Fourier coefficients with integrate().
For example, I can easily calculate a_k for k=1 as shown below, however I would like to succinctly calculate an array of a_k for k=1:N, without using a for loop.
k =1;
fun = @(x) cos(k*x)./sin(x);
a_k = integral(fun,x1,x2);
Any suggestions?
Cheers!
Edit: Sorry, I meant integral() function in the first sentence.

Best Answer

Of course, the limits will matter. I will guess if they include 0, for example, you may have a problem.
syms k x
x1 = pi/4;
x2 = pi/2;
F = cos(k*x)/sin(x);
Fcoef = arrayfun(@(K) int(subs(F,k,K),x1,x2),1:10)
Fcoef =
[ log(2)/2, log(2^(1/2) + 1) - 2^(1/2), log(2)/2 - 1, log(2^(1/2) + 1) - (2*2^(1/2))/3, log(2)/2, log(2^(1/2) + 1) - (7*2^(1/2))/15, log(2)/2 - 1/3, log(2^(1/2) + 1) - (64*2^(1/2))/105, log(2)/2 - 1/3, log(2^(1/2) + 1) - (227*2^(1/2))/315]
Note the odd terms show one pattern, the even terms another.
Fcoef(1:2:end)
ans =
[ log(2)/2, log(2)/2 - 1, log(2)/2, log(2)/2 - 1/3, log(2)/2 - 1/3]
Fcoef(2:2:end)
ans =
[ log(2^(1/2) + 1) - 2^(1/2), log(2^(1/2) + 1) - (2*2^(1/2))/3, log(2^(1/2) + 1) - (7*2^(1/2))/15, log(2^(1/2) + 1) - (64*2^(1/2))/105, log(2^(1/2) + 1) - (227*2^(1/2))/315]
I don't want to forget the zero'th order term.
int(subs(F,k,0),x1,x2)
ans =
log(2^(1/2) + 1)
If you prefer to do this numerically using integral, you can do so easily enough. But the integrate function would not apply in any case.
Related Question