I'm still a beginner on MATLAB and I'm trying to write a real-time code to implement a DSP system, but an error keeps showing up (Array Indices must be positive or integers)

3 次查看（过去 30 天）
Laura2022-11-24

So, the system I'm impleminting is a DSP system with LPFs and HPFs, along with mixers and downsamplers and upsamplers. I have generated the input, sampled it, and then tried to pass it through the LPF and HPF, but an error keeps showing up after h1 and h2 are executed which is (Index in position 2 is invalid. Array indices must be positive integers or logical values). The code is as follows:
clear all; close all;
rng default
%sampling function x(t)=cos(2*pi*500*t)+0.5*cos(2*pi*3500*t), defined as xs[n],
%f1=500, f2=3500, fs=8KHz
f1=500;
f2=3500;
fs=8000;
n=(0:10000); %running program for 10k samples
xs(1,n+1)=cos((2*pi*f1*n)/fs)+0.5*cos((2*pi*f2*n)/fs);
%passing xs through LPF h1 and HPF h2
h1=fir1(64,0.5,'low');
h2=fir1(64,0.5,'high');
h11=[h1,zeros(1,(length(xs)-length(h1)))];
h1_mirror=h11(1,end:-1:1);
for i=0:(2*length(n)-1);
y1(1,i+1)=h1_mirror(1,(end-i):1:end)*xs(1,1:i+1)';
end
Index in position 2 is invalid. Array indices must be positive integers or logical values.
h22=[h2,zeros(1,length(xs)-length(h2))];
h2_mirror=h22(1,end:-1:1);
for i=0:(2*length(n)-1)
y2(1,i+1)=h2_mirror(1,(end-i):1:end)*xs(1,1:i+1)';
end
%downsampling y1 and y2 by 2
j=0;
for i=0:(2*length(n)-1)
y3(1,i+1)=y1(1,j+1);
y4(1,i+1)=y2(1,j+1);
j=j+2;
if j==length(n)*2
break
end
end
%convolving with mixer
a=(0:1);
mixer1=a;
mixer2=1-a;
y5=y3*mixer1;
y6=y4*mixer2;
y5=[y5,zeros(1,3)];
y6=[y6,zeros(1,3)];
%up sampling y5 and y6 by factor of 2
j=2;
for i=0:2*length(n);
if mod(i,2)==0;
if i==0;
y7(1,i+1)=y5(1,i+1);
y8(1,i+1)=y6(1,i+1);
else
y7(1,i+1)=y5(1,j);
y8(1,i+1)=y6(1,j);
j=j+1;
end
else
y7(1,i+1)=0;
y8(1,i+1)=0;
end
end
%passing y7 through LPF h1
h12=[h1,zeros(1,(length(y7)-length(h1)))];
h12_mirror=h12(1,end:-1:1);
for i=0:(2*length(n)-1);
y9(1,i+1)=h12_mirror(1,(end-i):1:end)*y7(1,1:i+1)';
end
%passing y8 through HPF h2
h21=[h2,zeros(1,length(y8)-length(h2))];
h21_mirror=h21(1,end:-1:1);
for i=0:(2*length(n)-1)
y10(1,i+1)=h21_mirror(1,(end-i):1:end)*y8(1,1:i+1)';
end
Y=y9+y10;

采纳的回答

William Rose 2022-11-25
Look at the loop where the error occurs:
for i=0:(2*length(n)-1);
y1(1,i+1)=h1_mirror(1,(end-i):1:end)*xs(1,1:i+1)';
end
2*length(n)-1=20001. When i=10001, the value of the second index in h1_mirror(), on the right side, is
(end-i):1:end), and "end" =10001 for h1_mirror, so this equals (0:1:10001), and the zero index value is not allowed, since Matlab arrays sta with index 1 (unlike Labview arrays which start with 0).
The problem just gets worse as the for loop continues, because the starting value (end-i) becomes more and more negative.

类别

Find more on Applications in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by