how to fill a matrix without using loop in matlab?

8 visualizaciones (últimos 30 días)
Niloufar
Niloufar el 10 de Oct. de 2022
Comentada: Image Analyst el 10 de Oct. de 2022
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
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.
Image Analyst
Image Analyst el 10 de Oct. de 2022
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 Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by