Index exceeds the number of array elements (0)

조회 수: 19 (최근 30일)
Trinh Bac
Trinh Bac 2022년 1월 9일
댓글: Trinh Bac 2022년 1월 9일
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