why does preallocating space for array of structures by brute force leave my editor upset?
1 次查看(过去 30 天)
显示 更早的评论
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 个评论
回答(2 个)
James Tursa
2013-11-24
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
2013-11-24
编辑:Matt J
2013-11-24
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 个评论
Matt J
2013-11-24
编辑:Matt J
2013-11-24
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.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Data Type Conversion 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!