Making Matlab throw an error on index out of bounds
12 views (last 30 days)
Show older comments
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
0 Comments
Accepted Answer
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
on 17 Oct 2014
Actually, the's undoubtedly less overhead than the assert route...good thinking! :)
More Answers (2)
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).
0 Comments
See Also
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!