Protect the size of a preallocated matrix

3 views (last 30 days)
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.

Accepted Answer

Giuseppe Inghilterra
Giuseppe Inghilterra on 22 Feb 2020
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).

More Answers (0)

Products

Community Treasure Hunt

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

Start Hunting!