Protect the size of a preallocated matrix

1 次查看(过去 30 天)
I am trying to protect the preallocated size of a matrix, to avoid making mistakes, and getting/giving an error when the matrix size changes, without having to check the size everytime I do an iteration. Consider the following code.
>> A = zeros(2,2);
>> A(1,3) = 5
A =
0 0 5
0 0 0
I am aware I can check the size of the matrix everytime I change it. I am wondering however, whether Matlab can give me an error/warning, since you do get a warning with the following code:
A = [];
for i = 0:5
A = [A;eye(2)];
end % Warning: The variable A appears to change size at every iteration. Consider preallocating for speed.
If Matlab could give an error, I would preferably get this in the command window.

采纳的回答

Giuseppe Inghilterra
Hi,
in MATLAB numeric arrays are free to change size, i.e. if you add an element outside intial defined dimension, then array will be extended and no warning/error is shown.
You can define a user defined class (with a object oriented programming approach) in order to fix dimension of your numeric arrays. Otherwise you should check frequently size of your array and show a custom message on command window (by usind disp function) if size changes along code (but it is not a real solution).

更多回答(0 个)

类别

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

产品

Community Treasure Hunt

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

Start Hunting!

Translated by