Index exceeds array bounds for nested for loop

As I am running the loop separately for a limited values, it is given the correct result. The moment i add a nested for loop, it shows an error stating "Index Exceeds array bounds". Data file is attached along with this.
For the reference, i am attaching the code:
datafile= importdata('abc.txt') %input data file
x=20; %total number of elements to be considered in one slot
g= ones(x,1)/x; %unit sample response
i=x; %initial value
len=193; %total number of elements in data file
z=datafile.^3; %cube of data present in file
s=zeros(x,1) %initialise sum as 0
for i = x:len-1 %Loop to calculate sum
for j = i-x+1:i
r(j) = z(j)* g(j);
s(i) = s(i)+r(j);
end
end

 Akzeptierte Antwort

KALYAN ACHARJYA
KALYAN ACHARJYA am 26 Jun. 2019

0 Stimmen

j=i-x+1:i
firse case of for loop
i=x:len-1
where x=20, which is i first iterate value
Next loop
j =i-x+1:i
So
j=20-20+1:i
>> j=1:i
Where
i=x:len-1
Everytime j length changes depends on i, confusing
>> x=20; %total number of elements to be considered in one slot
g= ones(x,1)/x; %unit sample response
>> length(g)
ans =
20
The length of g is 20, but you iterrate the code beyond that limit for g, how it get the respective value
r(j) = z(j)* g(j);
%..............^
Please ensure for z too.
when for loop iterate
j=1, z(1) ok
j=2: z(2) ok
....
.....
if somehow j=21, z(21) is not avaliable
Please ensure the case, to avoid the error

4 Kommentare

shona sharma
shona sharma am 26 Jun. 2019
All values of z are available and I have changed g= ones(len,1)/x ,but still it is showing the same error for s(i) = s(i)+r(j)
KALYAN ACHARJYA
KALYAN ACHARJYA am 26 Jun. 2019
Bearbeitet: KALYAN ACHARJYA am 26 Jun. 2019
Comment on Initial code:
At first look code seems mess,please explain what you are trying to do on abc file?
first for loop 2nd iteration when i=21
Second for loop
j=i-x+1:i
which becomes
j=21-20+1:21
j=2:21
%....^ then g(21) is not avaliable
Requested you to read array indexing.
KALYAN ACHARJYA
KALYAN ACHARJYA am 26 Jun. 2019
Bearbeitet: KALYAN ACHARJYA am 26 Jun. 2019
Are you looking for this one, no error please check the result- I have changed g and s, length(datafile), it result 193, same as len s you mentioned
datafile= importdata('abc.txt'); %input data file
x=20; %total number of elements to be considered in one slot
g=ones(length(datafile),1)/x; %unit sample response
i=x; %initial value
z=datafile.^3; %cube of data present in file
s=zeros(length(datafile),1); %initialise sum as 0
r=[]; % Preallocation recomended
s=[];
for i=x:length(datafile)-1 %Loop to calculate sum
for j=i-x+1:i
r(j)=z(j)* g(j);
s(i)=s(i)+r(j);
end
end
Please do confirm?

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Community Treasure Hunt

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

Start Hunting!

Translated by