Reputation: 459
I have matrix A which is a 1*11470 struct and each A, for example A(1,1) has two elements, nPoints and matrix. I am going to do some calculations and after these calculations, number of elements in the A.matrix will increase 8 times but A.nPoints will be same. I want to do preallocation for this process but I could not find out how. Could you please help me?
note: To make my question clearer, I added two screenshots. What I want is, for example A(1,2).matrix have 3 elements. After doing certain calculations I am going to have 24 elements inside that matrix and I need to preallocate for example a A2 matrix, which has the same length (1*110470) as A, same size for nPoints but 8 times greater size for A(1,k).matrix.
Regards,
Upvotes: 0
Views: 621
Reputation: 352
I guess this can solve your problem:
B = struct ('nPoints',repmat({zeros(1)},1,110470), 'matrix',repmat ({zeros([(max([tracks(:).nPoints])^3) 3])},1,110470));
If it does not please let me know.
Upvotes: 1
Reputation: 2028
I could not follow the exact details of your problem, but the general solution for preallocating a matrix that changes in size is to initialize it from the beginning to it's maximum size. Then if you temporarily need to save a smaller set of numbers inside it, do so by indexing into it rather than resetting its size.
For example, if the maximum size you will need is 1x11470, initialize the variable to this size
a = NaN(1, 11470);
Then if you need to store a smaller sized vector inside it, you would do this
a(1:5) = rand(1,5);
If you need to access this vector, then you could either
1. Find it's indices on the fly,
a(~isnan(a))
2. Keep track of the size of your subarray every time you modify it
a.mat = nan(1,11470)
a.idx = 5;
a.mat(1:a.idx) = rand(1,a.idx);
If you're concerned with speed then the second method is superior.
Upvotes: 1