how to fill a matrix without using loop in matlab?

조회 수: 7 (최근 30일)
Niloufar
Niloufar 2022년 10월 10일
댓글: Image Analyst 2022년 10월 10일
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