Why does exceeding array index in this program not show an error?
2 views (last 30 days)
Show older comments
This is most basic code to reproduce my problem:
clear all; clc; close;
R = 64;
array_b = zeros(1, 1000);
for i = 1:10000
for kk=15:-1:2, % if ,WOLA_R=64
array_b(1,(kk+1)*R:-1:kk*R+1)=array_b(1,kk*R:-1:(kk-1)*R+1);
end
end
Running this program does not show any errors. If I put a breakpiunt at the line
array_b(1,(kk+1)*R:-1:kk*R+1)=array_b(1,kk*R:-1:(kk-1)*R+1);
and try to view the value of array_b(1,(kk+1)*R:-1:kk*R+1), I get
??? Index exceeds matrix dimensions.
which is what I expect. Size of array_b is (1, 1000) and for kk = 15 (first iteration of the loop), (kk+1)R:-1:kkR+1 = 1024 > 1000, so I should get an error.
But if I run the program normally I don't get an error. Why is that? This is supposed to copy the contents of array_b from lower indices to higher indices, 64 elements at a time. During the first iteration of the loop, if it does not make an error, where do the elements that are supposed to go from 1001 to 1024 go to?
0 Comments
Answers (1)
per isakson
on 26 Jun 2020
Edited: per isakson
on 26 Jun 2020
Because there are values of the second index, which exceeds 1000 (as you have noticed)
K>> (kk+1)*R:-1:kk*R+1
ans =
Columns 1 through 6
1024 1023 1022 1021 1020 1019
Columns 7 through 12
1018 1017 1016 1015 1014 1013
the assignment then increases (silently) the size of array_b
K>> whos array_b
Name Size Bytes Class Attributes
array_b 1x1024 8192 double
Matlab works that way
K>> a=1
a =
1
K>> a(3)=3;
K>> a
a =
1 0 3
2 Comments
per isakson
on 26 Jun 2020
"1024 elements long" pre-allocating to the exact size makes the program a bit faster. I cannot think of any other difference. Since you start by assigning to the highest index, I guess you could save a tine bit of time by skipping the pre-allocation. That was once true.
See Also
Categories
Find more on Matrix Indexing 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!