I am writing a code for DFT and getting this error. 'subscript indices must either be real positive integers or logicals'. My code is as under. Can somebody help me with it? I have used both logical and round commands but still getting the same error

clear all;
clc;
f=60;
Fs=57600;
T=1/Fs;
N=960;
t=0:0.000017:0.02;
m=0;
%x=sin(2*pi*f*t);
y=sqrt(2)*15.66*cos(2*pi*f.*t);
for n=1:960;
x(n)= y(n)
real(n)=cos(2*pi*(1/960)*(n-1));
imag(n)=sin(2*pi*(1/960)*(n-1));
m=m+1
end
for n=1:960;
F(n)=y(n)*(real(n)+imag(n))
end
plot(t,F(n))

1 Comment

You never use t in your computation, but you try to plot against t.
After the "for" loop just before your plot(), n will end up with the value 960. When you try to plot(t,F(n)) you are telling it to plot(t,F(960)) where F(960) is a single value. That will produce a plot, but it will not be a useful plot.
Please note that when you assign to F(n) you are not creating a formula, you are assigning a definite numeric value.

Sign in to comment.

 Accepted Answer

Hafsa - I can run your above code without any errors, so please clarify at which line the subscript indices must either be real positive integers or logicals error is being raised from. Typically, this error message indicates that the code is trying to access an element of an array with a non-integer index. For example, the following code generates this same error
myData = randi(255,42,1);
myData(1.4)
because I am trying to index into the myData array using 1.4.
I noticed that your time interval is for 0.02 seconds. Perhaps you should start with the simpler case of the time interval being for one second initialized as
t = linspace(0,1-T,Fs);
y = sin(2*pi*f*t);
Also, I don't think that your DFT has been set up correctly. Typically, there is an outer and an inner for loop (see DFT). Try something like
N = 960;
F = zeros(N,1);
for m=0:N-1
dftSum = 0;
for n=0:N-1
dftSum = dftSum + y(n+1)*(cos(2*pi*n*m/N) - 1i*sin(2*pi*n*m/N));
end
F(m+1) = dftSum;
end
Note also that you want to plot the result of the DFT versus frequency and not time
freq = 0:Fs/N:(N-1)*Fs/N;
plot(freq,abs(F))

More Answers (0)

Categories

Find more on Function Creation in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!