您可以创建一个子类double
并限制分配subsasgn
method:
classdef dbl < double
methods
function obj = dbl(d)
obj = obj@double(d);
end
function obj = subsasgn(obj,s,val)
if strcmp(s.type, '()')
mx = cellfun(@max, s.subs).*~strcmp(s.subs, ':');
sz = size(obj);
nx = numel(mx);
if nx < numel(sz)
sz = [sz(1:nx-1) prod(sz(nx:end))];
end
assert(all( mx <= sz), ...
'Index exceeds matrix dimensions.');
end
obj = subsasgn@double(obj, s, val);
end
end
end
所以现在当你预分配使用时dbl
>> z = dbl(zeros(3))
z =
dbl
double data:
0 0 0
0 0 0
0 0 0
Methods, Superclasses
所有方法用于double
现在继承于dbl
你可以照常使用它,直到你将一些东西分配给z
>> z(1:2,2:3) = 6
z =
dbl
double data:
0 6 6
0 6 6
0 0 0
Methods, Superclasses
>> z(1:2,2:5) = 6
Error using dbl/subsasgn (line 9)
Index exceeds matrix dimensions.
我还没有对其进行基准测试,但我预计这对性能影响不大。
如果您希望值的显示看起来正常,您可以重载display
方法还有:
function display(obj)
display(double(obj));
end
Then
>> z = dbl(zeros(3))
ans =
0 0 0
0 0 0
0 0 0
>> z(1:2,2:3) = 6
ans =
0 6 6
0 6 6
0 0 0
>> z(1:2,2:5) = 6
Error using dbl/subsasgn (line 9)
Index exceeds matrix dimensions.
>> class(z)
ans =
dbl