Index exceeds the number of array elements (0)

20 次查看(过去 30 天)
When I run this code, there is a problem like this:
Index exceeds the number of array elements (0).
Error in Untitled9 (line 39)
plot (t,abs(Xn(1:k)));
And this is a code:
clc;
close all;
Fs=500;
Ts=1/Fs;
Tsin=3;
t=0:Ts:1-Ts;
x1n=cos(50*pi*t);
t=1:Ts:2-Ts;
x2n=cos(50*pi*t)+cos(100*pi*t);
t=2:Ts:3-Ts;
x3n=cos(50*pi*t)+cos(100*pi*t)+cos(150*pi*t);
t=3:Ts:Tsin;
xn=[x1n x2n x3n zeros(size(t))];
M=128;
L=30;
Nx=length (xn);
k=(Nx-L)/(M-L);
k=floor(k);
R=M-L;
g=gausswin(M);
Xn=[];
for n=1:k
X=xn(((n-1)*R+1):(n-1)*R+M);
Xm=fft(X,M);
figure(1);
plot3(repmat(n,1,M),1:M,abs(fft(X,M)));
hold on
end
t=0:Ts:Tsin;
figure(2)
subplot(1,2,1);
plot(t,xn);
xlabel('t(s)');
ylabel('Amplitude');
title ('Input sequence');
subplot (1,2,2);
plot (t,abs(Xn(1:k)));
Index exceeds the number of array elements. Index must not exceed 0.
xlabel('t(s)');
ylabel('Amplitude');
title('STFT');
How to solve this problem? Please help me

采纳的回答

Cris LaPierre
Cris LaPierre 2022-1-9
编辑:Cris LaPierre 2022-1-9
The problems is you are trying to index an empty array. You define Xn=[]; and never assign it a value, but then try to index it like it has a value.
Is Xm a typo? Did you mean to use Xn? If so, note that I had to adjust the number of t values to make the number of Xn values in the plot command: both have to have 1:k values.
clc;
close all;
Fs=500;
Ts=1/Fs;
Tsin=3;
t=0:Ts:1-Ts;
x1n=cos(50*pi*t);
t=1:Ts:2-Ts;
x2n=cos(50*pi*t)+cos(100*pi*t);
t=2:Ts:3-Ts;
x3n=cos(50*pi*t)+cos(100*pi*t)+cos(150*pi*t);
t=3:Ts:Tsin;
xn=[x1n x2n x3n zeros(size(t))];
M=128;
L=30;
Nx=length (xn);
k=(Nx-L)/(M-L);
k=floor(k);
R=M-L;
g=gausswin(M);
Xn=[];
for n=1:k
X=xn(((n-1)*R+1):(n-1)*R+M);
Xn=fft(X,M);
figure(1);
plot3(repmat(n,1,M),1:M,abs(fft(X,M)));
hold on
end
t=0:Ts:Tsin;
figure(2)
subplot(1,2,1);
plot(t,xn);
xlabel('t(s)');
ylabel('Amplitude');
title ('Input sequence');
subplot (1,2,2);
plot (t(1:k),abs(Xn(1:k)));
xlabel('t(s)');
ylabel('Amplitude');
title('STFT');

更多回答(1 个)

the cyclist
the cyclist 2022-1-9
You have confusingly defined both Xn and xn. You are trying to access the variable Xn, which is an empty array.
I'm guessing you intended to access xn instead, but I haven't tried to figure out what you actually wanted to do.

类别

Help CenterFile Exchange 中查找有关 2-D and 3-D Plots 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by