Protect the size of a preallocated matrix
1 visualizzazione (ultimi 30 giorni)
Mostra commenti meno recenti
Martijn Kortenhoeven
il 22 Feb 2020
Commentato: Martijn Kortenhoeven
il 22 Feb 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.
0 Commenti
Risposta accettata
Giuseppe Inghilterra
il 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).
Più risposte (0)
Vedere anche
Categorie
Scopri di più su Logical in Help Center e File Exchange
Prodotti
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!