Protect the size of a preallocated matrix

1 visualización (últimos 30 días)
Martijn Kortenhoeven
Martijn Kortenhoeven el 22 de Feb. de 2020
Comentada: Martijn Kortenhoeven el 22 de Feb. de 2020
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.

Respuesta aceptada

Giuseppe Inghilterra
Giuseppe Inghilterra el 22 de Feb. de 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).

Más respuestas (0)

Categorías

Más información sobre Logical en Help Center y File Exchange.

Productos

Community Treasure Hunt

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

Start Hunting!

Translated by