Why does exceeding array index in this program not show an error?

1 次查看(过去 30 天)
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?

回答(1 个)

per isakson
per isakson 2020-6-26
编辑:per isakson 2020-6-26
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 个评论
mahaju
mahaju 2020-6-26
Thank you very much. So if I initially make array_b 1024 elements long, does the program behave exactly the same way?
per isakson
per isakson 2020-6-26
"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.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by