This is not a fully worked example (see disclaimer after the code!) but it shows one idea...
You could (at least while debugging your code), use the following class in place of zeros to allocate your original variable.
Subsequent use of the data outside of the bounds of the originally allocated size would result in an 'Index exceeds matrix dimensions.' error.
For example:
>> n = 3;
>> x = zeros_debug(n, 1)
x =
0
0
0
>> x(2) = 32
x =
0
32
0
>> x(5) = 3
Error using zeros_debug/subsasgn (line 42)
Index exceeds matrix dimensions.
>>
The class code:
classdef zeros_debug < handle
properties (Hidden)
Data
end
methods
function obj = zeros_debug(M,N)
if nargin < 2
N = M;
end
obj.Data = zeros(M,N);
end
function sref = subsref(obj,s)
switch s(1).type
case '()'
if length(s)<2
% Note that obj.Data is passed to subsref
sref = builtin('subsref',obj.Data,s);
return
else
sref = builtin('subsref',obj,s);
end
otherwise,
error('zeros_debug:subsref',...
'Not a supported subscripted reference')
end
end
function obj = subsasgn(obj,s,val)
if isempty(s) && strcmp(class(val),'zeros_debug')
obj = zeros_debug(val.Data);
end
switch s(1).type
case '.'
obj = builtin('subsasgn',obj,s,val);
case '()'
if strcmp(class(val),'double')
switch length(s(1).subs{1})
case 1,
if s(1).subs{1} > length(obj.Data)
error('zeros_debug:subsasgn','Index exceeds matrix dimensions.');
end
case 2,
if s(1).subs{1} > size(obj.Data,1) || ...
s(1).subs{2} > size(obj.Data,2)
error('zeros_debug:subsasgn','Index exceeds matrix dimensions.');
end
end
snew = substruct('.','Data','()',s(1).subs(:));
obj = subsasgn(obj,snew,val);
end
otherwise,
error('zeros_debug:subsasgn',...
'Not a supported subscripted assignment')
end
end
function disp( obj )
disp(obj.Data);
end
end
end
There would be considerable performance implications (and problems stemming from using a class inheriting from handle) but it seemed like an interesting solution to the original problem.
for ix=1:n
? That way, if you happen to setn
to the wrong value, you only have to fix one line of code. – Humbertohumble