FFT of sine wave not plotting

조회 수: 2 (최근 30일)
Eva Carrillo
Eva Carrillo 2019년 11월 25일
clc;
spectrum=[];
omega=2*pi*10;
t=0:0.001:10;
f=0:0.1:500;
for n=1:0.001:10
y(n)=sin(omega*y(n));
spectrum=abs(fft((y)));
for i=1:10001
if spectrum(i)<5001
spectrum2(i)=spectrum(i);
end
if spectrum(i)>5001
spectrum3(i)=spetrum(i);
end
end
end
plot(f,spectrum);
hold on;
xlabel('frequency');
hold on;
ylabel('power');
hold on;
xlim([0 1]);
So I have a loop that stores 10001 values into an array. I need to be able to plot the values that are greater than, or less that 5001. I developed this code but its not working. Help is greatly appreciated!
  댓글 수: 1
KALYAN ACHARJYA
KALYAN ACHARJYA 2019년 11월 25일
There are issues in the code, likewise
for n=1:0.001:10;
y(n)=
For the above n=1, first iteration will evaluate y(1)..OK
2nd interation n=0.001, which will evaluate y(0.001)..Not OK
Matlab only allows pisitive integer indexing, Hence , y(1), y(2), y(3)...so on...OK. But y(0),y(-2),y(0.04) are not allowed in Matlab Platform.
Plese do the modification, its easy to implement the code of FFT of sine wave

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

답변 (1개)

Constantino Carlos Reyes-Aldasoro
Constantino Carlos Reyes-Aldasoro 2019년 11월 25일
In addition to the previous comment 2 issues:
1) FFT will give a complex answer so you will need to plot the absolute values like
plot(abs(spectrum))
This is better than using the abs previously as you may need to use the phase, or imaginary parts for other calculations
2) you are looping as it is normally done in C or other programming languages. In Matlab you can do this as matrix operations, no need to loop
omega=2*pi*10;
t=0:0.001:10;
y=sin(omega*t);
spectrum=fft(y);
spectrum2=spectrum(1:5000);
spectrum3=spectrum(5001:end);
plot(abs(fftshift(spectrum)))
also notice that you had a typo
spectrum3(i)=spetrum(i);

Community Treasure Hunt

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

Start Hunting!

Translated by