Array indices must be positive integers or logical values.

1 view (last 30 days)
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*t(n));
spectrum=abs(fft((y)));
end
plot(f,spectrum);
hold on;
xlabel('frequency');
hold on;
ylabel('power');
hold on;
xlim([0 1]);
I keep getting:
%Array indices must be positive integers or logical values.
%Error in SINEfunction2 (line 8)
y(n)=sin(omega*t(n));
I've tried many ways to try to fix it but can't figure it out
Help is appreciated!

Accepted Answer

KALYAN ACHARJYA
KALYAN ACHARJYA on 19 Nov 2019
Edited: KALYAN ACHARJYA on 19 Nov 2019
Please check it has modified (slightly), no need of loop here.
omega=2*pi*10;
t=0:0.001:10;
f=linspace(0,500,length(t));
n=1:0.001:10;
y=sin(omega*t);
spectrum=abs(fft((y)));
plot(f,spectrum);
xlabel('frequency');
ylabel('power');
%xlim([0 1]);

More Answers (1)

David Hill
David Hill on 19 Nov 2019
clc;
omega=2*pi*10;
t=0:0.001:10;
f=0:0.1:500;
for n=1:length(t)
y(n)=sin(omega*t(n));
end
spectrum=abs(fft(y));%does not need to be in the loop
plot(t,spectrum);%f needs to be the same length as t
hold on;
xlabel('frequency');
hold on;
ylabel('power');
hold on;
xlim([0 1]);

Community Treasure Hunt

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

Start Hunting!