why does preallocating space for array of structures by brute force leave my editor upset?
1 vue (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Consider the bit of code
for k=1:10
s(k).this = 0;
s(k).that = [0, 0, 0];
end
for k=1:10
s(k).this = 1/k;
s(k).that = [k, k^2, k^3];
end
The first loop causes the editor to complain that the s is changing size with every loop iteration and should be preallocated. I get that. But I don't care since this loop would only run once. What I don't get is why the editor is making the same complaint about the 2nd loop. s is already filled. I'm only changing the values. Aren't I?
0 commentaires
Réponses (2)
James Tursa
le 24 Nov 2013
As shown, I agree that s is already allocated for the 2nd loop. The editor may simply not be smart enough to recognize this. Is there anything in-between these loops that you are not showing us?
Matt J
le 24 Nov 2013
Modifié(e) : Matt J
le 24 Nov 2013
I get that. But I don't care since this loop would only run once.
But why use the first loop at all when it is both unnecessary and inefficient? All you need for pre-allocation purposes is to assign the final struct array element
s(10).this = [];
s(10).that = [];
Note that your second loop is not getting any advantage from pre-assigning non-empty values to the s(i).this and s(i).that. Fields act merely as pointers to data. All the 2nd loop does is point the fields to the new data [k, k^2, k^3] and 1/k.
It would be different if you were doing some sort of in-place operation on the fields like
s(k).this(1)=1;
But in your case, you are generating completely new data in the 2nd loop and overwriting the fields completely.
2 commentaires
Matt J
le 24 Nov 2013
Modifié(e) : Matt J
le 24 Nov 2013
How would your solution work without specifying the size of the array s(10).that ?
The size of the struct array? If you don't know its size in advance, I don't know what "pre-allocation" would mean.
If you mean the actual contents of the field s(10).that, you would set it to empty as I showed.
And different data require different amounts of memory (doubles take more than uints) ? How do I account for that?
Don't see how that applies to you. The data you are pre-allocating are empty struct elements, not doubles or uints. As I mentioned, there is no advantage to pre-allocating the contents of the fields, given what you've said your code is doing later.
Voir également
Catégories
En savoir plus sur Data Type Conversion dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!