필터 지우기
필터 지우기

Need to solve Fourier Series script

조회 수: 1 (최근 30일)
NANDEESWARAN
NANDEESWARAN 2023년 11월 18일
댓글: NANDEESWARAN 2023년 11월 18일
clear all;clc;
x = 0:0.01:1;
for i = 1: size(x,2)
y(i) = exact(x(i));
f(i) = fourier(x(i),3);
g(i) = fourier(x(i),6);
end
function func = phi(x,n)
func = cos(pi * (n - 1/2) * x);
end
function coef = c(n)
beta = pi * (2 * n - 1);
coef = 8 * (cos(beta / 4) - cos(beta / 2)) / beta^2;
end
function f = fourier(x,N)
f = 0;
for n = 1: N
f = f + c(n) * phi(x,n);
end
end
function f = exact(x)
if x < 1/2
f = 1/2;
else
f = 1 - x;
end
end
plot(x,y,'-','LineWidth',5,x,f,'--','LineWidth',5,x,g,'-','LineWidth',5);
legend('Exact','Fourier (3 terms)','Fourier (6 terms)');

채택된 답변

madhan ravi
madhan ravi 2023년 11월 18일
plot(x,y,'-',x,f,'--',x,g,'-','LineWidth',5);
legend('Exact','Fourier (3 terms)','Fourier (6 terms)'); % use this line before function
  댓글 수: 2
madhan ravi
madhan ravi 2023년 11월 18일
You could preallocate variables before the for loop
NANDEESWARAN
NANDEESWARAN 2023년 11월 18일
Thanks Sir.

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

VBBV
VBBV 2023년 11월 18일
if you have the entire code in one script file, then you can put all the functions after the plot function call as below otherwise,if you have them in separate function files, you can just call plot function as below
clear all;clc;
x = 0:0.01:1;
for i = 1: size(x,2)
y(i) = exact(x(i));
f(i) = fourier(x(i),3);
g(i) = fourier(x(i),6);
end
hold on
plot(x,y,'-','LineWidth',2)
plot(x,f,'--','LineWidth',2)
plot(x,g,'-','LineWidth',2);
legend('Exact','Fourier (3 terms)','Fourier (6 terms)');
function f = exact(x)
if x < 1/2
f = 1/2;
else
f = 1 - x;
end
end
function f = fourier(x,N)
f = 0;
for n = 1: N
f = f + c(n) * phi(x,n);
end
end
function func = phi(x,n)
func = cos(pi * (n - 1/2) * x);
end
function coef = c(n)
beta = pi * (2 * n - 1);
coef = 8 * (cos(beta / 4) - cos(beta / 2)) / beta^2;
end
  댓글 수: 1
NANDEESWARAN
NANDEESWARAN 2023년 11월 18일
Thanks Sir . I appreciate your reply, Its working now.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Surface and Mesh Plots에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by