hello
I have written a function for fourier series but when i try to plot it ,only the consine one shows up did I forget something ? Danke schön
function ft = signal(S,t,A,M,T,N)
for n=1:N
if S=="square"
ft=M+sum(((4*A)./(n.*pi)).*sin((n.*pi)/2).*cos((2*n.*pi.*t)./T));
elseif S=="triangle"
ft=M+sum(((8*A)./(n.^2*pi^2)).*cos((2*n*pi.*t)./T));
elseif S=="saw"
ft=M+sum(-1^(n+1).*(2*A./n.^pi).*sin((2*n.*pi*t)./T));
elseif S=="cosine"
ft=M+A*cos((2*pi.*t)./T);
end
end
%%plot part
M=0;
A=1;
T=10;
t=0:0.1:60;
N=10;
grid on
ft=signal("square",t,A,M,T,N);
plot(t,ft,'r')
hold on
ft=signal("triangle",t,A,M,T,N);
plot(t,ft,'b')
hold on
ft=signal("saw",t,A,M,T,N);
plot(t,ft,'g')
hold on
ft=signal("cosine",t,A,M,T,N);
plot(t,ft,'k')
%%

 채택된 답변

Star Strider
Star Strider 2022년 2월 24일
편집: Star Strider 2022년 2월 24일

1 개 추천

Try this —
%%plot part
M=0;
A=1;
T=10;
t=0:0.1:60;
N=10;
figure
subplot(4,1,1)
ft=signal("square",t,A,M,T,N);
plot(t,ft,'r')
subplot(4,1,2)
ft=signal("triangle",t,A,M,T,N);
plot(t,ft,'b')
subplot(4,1,3)
ft=signal("saw",t,A,M,T,N);
plot(t,ft,'g')
subplot(4,1,4)
ft=signal("cosine",t,A,M,T,N);
plot(t,ft,'k')
%%
function ft = signal(S,t,A,M,T,N)
n=(1:N).';
if S=="square"
ft=M+sum(((4*A)./(n.*pi)).*sin((n.*pi)/2).*cos((2*n.*pi.*t)./T));
elseif S=="triangle"
ft=M+sum(((8*A)./(n.^2*pi^2)).*cos((2*n*pi.*t)./T));
elseif S=="saw"
ft=M+sum(-1.^(n+1).*(2*A./n.^pi).*sin((2*n.*pi*t)./T));
elseif S=="cosine"
ft=M+A*cos((2*pi.*t)./T);
end
end
The loop was not executing correctly. I eliminated the for loop and changed the code to use ‘n’ as a column vector to take advantage of MATLAB’s vectorisation abilities. (I plotted them as subplots because I wanted to see the individual results more clearly.) Otherwise (except for a minor change in the ‘saw’ calculation) the code is unchanged.
EDIT — (24 Feb 2022 at 15:06)
Changed original answer text to one that actually addresses the problem.
.

댓글 수: 2

Rayan  Maye
Rayan Maye 2022년 2월 24일
How dumb of me of not vectorizing n,thanks for your help mate
Star Strider
Star Strider 2022년 2월 24일
As always, my pleasure!

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

추가 답변 (1개)

Rayan  Maye
Rayan Maye 2022년 2월 24일

0 개 추천

Tried it ,did'nt work but thanks.I'm suspecting the problem is maybe a mistake that I did in the transcription of mathematical formulas.

카테고리

도움말 센터File Exchange에서 Annotations에 대해 자세히 알아보기

제품

릴리스

R2021b

태그

질문:

2022년 2월 24일

댓글:

2022년 2월 24일

Community Treasure Hunt

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

Start Hunting!

Translated by