Making Matlab throw an error on index out of bounds

12 views (last 30 days)
I'm curious if it's possible to force Matlab to throw an error when an an array with predefined size is indexed out of bounds. For example, I'd like the following code to throw an error instead of simply making "i" 11 elements long:
function i = test()
%#codegen
i=zeros(10,1);
for j=1:11
i(j) = 1;
end
end

Accepted Answer

Matt J
Matt J on 17 Oct 2014
Edited: Matt J on 17 Oct 2014
A subsref (right hand side indexing) operation will always throw an error if you index out of bounds. So, you could just insert one,
for j=1:11
discard=i(j); %will throw error if out of bounds.
i(j) = 1;
end
  2 Comments
dpb
dpb on 17 Oct 2014
Actually, the's undoubtedly less overhead than the assert route...good thinking! :)
Matt J
Matt J on 17 Oct 2014
Edited: Matt J on 17 Oct 2014
Depends how big the index array is though. If it's just a scalar, no big deal. but if instead of j, you had a 100x100 array of indices J, the subsref will allocate 100x100 memory for i(J) and you will have serious overhead.

Sign in to comment.

More Answers (2)

dpb
dpb on 17 Oct 2014
AFAIK, automagic reallocation is built in so deeply there's no way to avoid it. Best you can do is sotoo
assert(j>length(i), 'Array bound exceeded.')
in the loop before the access. This is bound to have highly detrimental effect on run time (as does bounds checking in compiled languages as well when turned on).

David
David on 17 Oct 2014
Thanks guys, sounds like there's no magic bullet :(

Products

Community Treasure Hunt

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

Start Hunting!