how to fill a matrix without using loop in matlab?

1 次查看(过去 30 天)
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

回答(1 个)

Torsten
Torsten 2022-10-10
编辑:Torsten 2022-10-10
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 个评论
Torsten
Torsten 2022-10-10
编辑:Torsten 2022-10-10
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 2022-10-10
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.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by