How to sum and plot a series of functions?

7 views (last 30 days)
Sem título.png
I have to plot the sum of this series, with N = 24, and N = 120. It's supposed to be a square wave, because of the gibbs phenomenon, but I just keep getting it wrong.
This is my code
:k = 1;
s = 1;
y = 120;
x = 27;
for k = 1:24;
a(k) =(2/pi)*((1-(-1)^k)/k)*sin(k*x);
end
for s = 1:120;
u(s) =(2/pi)*((1-(-1)^s)/s)*sin(s*x);
end
plot(a);
figure;
plot(u);
Thank you for your time!

Accepted Answer

Torsten
Torsten on 22 Nov 2018
n = 24;
k = 1:n;
part1 = @(x) sin(k*x)
part2 = (2/pi*(1-(-1).^k)./k).';
x = linspace(0,2*pi,100);
Snx = arrayfun(@(x)part1(x)*part2,x);
plot(x,Snx)
  2 Comments
Klaus Damasceno
Klaus Damasceno on 22 Nov 2018
It worked our perfectly! Would you care to explain about the arrayfun and the @? Also, would it work fine for n = 120?
Thanks Torsten!
Torsten
Torsten on 22 Nov 2018
Edited: Torsten on 22 Nov 2018
function main
n1 = 24;
x1 = linspace(0,2*pi,100);
Snx1 = series(n1,x1);
n2 = 120;
x2 = linspace(0,2*pi,200);
Snx2 = series(n2,x2);
plot(x1,Snx1,x2,Snx2)
end
function Sn = series(n,x)
part1 = @(x) sin((1:n)*x)
part2 = (2/pi*(1-(-1).^(1:n))./(1:n)).';
Sn = arrayfun(@(x)part1(x)*part2,x);
end

Sign in to comment.

More Answers (1)

madhan ravi
madhan ravi on 22 Nov 2018
Edited: madhan ravi on 22 Nov 2018
Loop not necessary use cumsum() instead
y = 120;
x = linspace(1,27,24);
k = 1:24;
a(k) =cumsum((2/pi).*((1-(-1).^k)/k).*sin(k.*x));
plot(x,a(k));
s = 1:120;
x=linspace(1,27,120);
u(s) =cumsum((2/pi).*((1-(-1).^s)./s).*sin(s.*x));
figure;
plot(x,u(s));
  11 Comments
Klaus Damasceno
Klaus Damasceno on 22 Nov 2018
I changed the Y also, so that I could plot it too. (matrix dimensions weren't the same)
y = linspace(-3*pi,3*pi,120);
x = linspace(-3*pi,3*pi,24);
k = 1:24;
a(k) =cumsum((2/pi).*((1-(-1).^k)/k).*sin(k.*x));
s = 1:120;
u(s) =cumsum((2/pi).*((1-(-1).^s)./s).*sin(s.*y));
plot(a(k));
figure;
plot(u(s));
madhan ravi
madhan ravi on 22 Nov 2018
x = linspace(-3*pi,3*pi,24);
k = 1:24;
a(k) =cumsum((2/pi).*((1-(-1).^k)/k).*sin(k.*x));
s = 1:120;
y = linspace(-3*pi,3*pi,120);
u(s) =cumsum((2/pi).*((1-(-1).^s)./s).*sin(s.*y));
plot(a(k));
figure;
plot(u(s));

Sign in to comment.

Categories

Find more on Graphics 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!