Pre allocation do not work ...
Mostra commenti meno recenti
Hi everyone,
I am a bit lost,
I ran a code this morning and the pre allocation do not work, it changes the size of my matrices with any reason,
So I did a small try like this :
n=3
x = zeros(1,n);
for ii=1:10
x( ii ) = ( ii );
end
%
Before I got an error because the size just exceeds... now it works, it changes the size of x, how to avoid that ?
Best regards,
1 Commento
Adam
il 3 Feb 2020
Pre-size it correctly! You pre-size it to 3 then put it in a for loop up to 10 assignging values to it. Where do you expect the next 7 elements to come from? You didn't pre-allocate those so the array grows in the loop.
Risposta accettata
Più risposte (1)
Gauthier Briere
il 3 Feb 2020
3 Commenti
Walter Roberson
il 3 Feb 2020
It would give the index error if you tried to read from a location before writing. For example x(ii, jj) = x(ii, jj) + ii;
I still don't get it!! Why are you expecting an error? The preallocation simply helps in speeding up the loop. See this answer for details:
Other than that the for loop will always overwrite the preallocated loop. If you MUST HAVE an error you can insert it manually like this:
n=3
x = zeros(1,n);
temp=length(x);
for ii=1:10
if ii>temp
error('Index exceeds preallocated matrix size')
break
end
x( ii ) = ( ii );
end
%
Gauthier Briere
il 3 Feb 2020
Categorie
Scopri di più su MATLAB in Centro assistenza e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!