Calculate continuous Fourier Series for 50 coefficients

3 views (last 30 days)
My code:
f = @(x) cos(3*x) - 0.5*sin(5*x) + 0.05*cos(54*x);
a0 = (1/pi)*integral(f,-pi,pi);
a50 = @(x) (1/pi)*integral(f*cos(50*x), -pi, pi);
for k = 1:1:49
rk = @(x) (1/pi)*integral(f*cos(k*x),-pi,pi)*cos(k*x) + (1/pi)*integral(f*sin(k*x),-pi,pi)*sin(k*x);
r = @(x) r + rk;
end
v = @(x) a0/2 + a50*cos(50*x) + r;
hold on
fplot(f, [-pi,pi], 'k')
fplot(v, [-pi,pi], 'r')
I am attempting to find the fourier series for f, as specified in my code. I am not an expereinced coder, and I believe I am calculating the Fourier coefficients incorrectly. When running the code, I get the following warnings:
Warning: Function behaves unexpectedly on array inputs. To improve performance, properly vectorize your
function to return an output with the same size and shape as the input arguments.
> In matlab.graphics.function.FunctionLine>getFunction
In matlab.graphics.function.FunctionLine/updateFunction
In matlab.graphics.function.FunctionLine/set.Function_I
In matlab.graphics.function.FunctionLine/set.Function
In matlab.graphics.function.FunctionLine
In fplot>singleFplot (line 237)
In fplot>@(f)singleFplot(cax,{f},limits,extraOpts,args) (line 192)
In fplot>vectorizeFplot (line 192)
In fplot (line 162)
In Hw5 (line 15)
Warning: Error updating FunctionLine.
The following error was reported evaluating the function in FunctionLine update: Undefined function
'mtimes' for input arguments of type 'function_handle'.
Warning: Error updating FunctionLine.
The following error was reported evaluating the function in FunctionLine update: Undefined function
'mtimes' for input arguments of type 'function_handle'.
From this, I only see the plot of f instead of v(x). v(x) is to be built by using the standard techniques of calculating Fourier coefficients. Any help is appreciated, thank you.

Accepted Answer

Shubham Gupta
Shubham Gupta on 25 Sep 2019
Try this :
r = @(x)0;
f = @(x) cos(3*x) - 0.5*sin(5*x) + 0.05*cos(54*x);
a0 = (1/pi)*integral(f,-pi,pi);
a50 = @(x) (1/pi)*integral(@(x)f(x).*cos(50*x), -pi, pi);
for k = 1:1:49
rk = @(x) (1/pi)*integral(@(x)f(x).*cos(k*x),-pi,pi)*cos(k*x) + (1/pi)*integral(@(x)f(x).*sin(k*x),-pi,pi)*sin(k*x);
r = @(x) r(x) + rk(x);
end
v = @(x) a0/2 + a50(x)*cos(50*x) + r(x);
hold on
fplot(f, [-pi,pi], 'k')
fplot(v, [-pi,pi], 'r')
You should not multiply or add scalar to function handle.
I hope this helps !

More Answers (0)

Categories

Find more on MATLAB Coder in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!