how to fill a matrix without using loop in matlab?

I want to find the coefficient of this fourier series without using loop.I mean filling an,bn and after that is it possible to plot hplot step by step without using loop
close all; clear; clc;
N = 6;
f = @(x) rectangularPulse(-1,1,x);
x = -2:0.001:2;
%2*p is the period
p = pi;
% the main function
plot(x,f(x),'LineWidth',2);
grid;
hold on;
grid minor;
xlim([-2 2]);
ylim([-0.1 1.1]);
x = linspace(-2,2,100).';
y = linspace(0,1,0.2);
a0 = (1/(2*p))*integral(f,-p,p);
an = zeros(1,N);
bn = zeros(1,N);
% calculate an and bn till N
for n=1:N
fan = @(x) rectangularPulse(-1,1,x).*cos((n*pi/p)*x);
an(1,n) = (1/p)*integral(fan,-p,p);
fbn = @(x) rectangularPulse(-1,1,x).*sin((n*pi/p)*x);
bn(1,n) = (1/p)*integral(fbn,-p,p);
end
% create the gif
for n = 1:N
An = an(:,(1:n));
Bn = bn(:,(1:n));
fs = a0 + sum(An.*cos((1:n).*x) + Bn.*sin((1:n).*x),2);
hPlot = plot(x,fs,'color','red','LineWidth',2);
drawnow;
if(n~=N)
delete(hPlot);
end
end

Respuestas (1)

Torsten
Torsten el 10 de Oct. de 2022
Editada: Torsten el 10 de Oct. de 2022
If you want to plot the partial sums of the Fourier series, you will have to keep the last loop, I guess.
close all; clear; clc;
N = 6;
f = @(x) rectangularPulse(-1,1,x);
x = -2:0.001:2;
%2*p is the period
p = pi;
% the main function
plot(x,f(x),'LineWidth',2);
grid;
hold on;
grid minor;
xlim([-2 2]);
ylim([-0.1 1.1]);
x = linspace(-2,2,100).';
y = linspace(0,1,0.2);
a0 = (1/(2*p))*integral(f,-p,p);
an = 1/p * integral(@(x) f(x).*cos((1:N)*pi/p*x),-p,p,'ArrayValued',1);
bn = 1/p * integral(@(x) f(x).*sin((1:N)*pi/p*x),-p,p,'ArrayValued',1);
fs = a0 + sum(an.*cos((1:N).*x) + bn.*sin((1:N).*x),2);
plot(x,fs,'color','red','LineWidth',2);

3 comentarios

Niloufar
Niloufar el 10 de Oct. de 2022
This isn't what I want.I want to create a gif to show gibbs phenomenon with this function as I sent the code.but the speed of the program is slow when I change N to larger numbers, I wanted to avoid using loops to speed it up
Torsten
Torsten el 10 de Oct. de 2022
Editada: Torsten el 10 de Oct. de 2022
If you want to plot the fourier series for different values of n, you will have to use a loop.
The loop to generate the coefficients an and bn is superfluous, as you can see above.
How many iterations do you have? Billions? If you use for n = 1 : 6, the "overhead" time to do six iterations is negligible. Your computer will do 6 iterations in nanoseconds. The bottleneck is what's happening inside the loop, not the looping itself.

Iniciar sesión para comentar.

Categorías

Más información sobre Loops and Conditional Statements en Centro de ayuda y File Exchange.

Preguntada:

el 10 de Oct. de 2022

Comentada:

el 10 de Oct. de 2022

Community Treasure Hunt

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

Start Hunting!

Translated by