0

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,

enter image description here

enter image description here

2
  • Can you try to simplify what exactly you're asking? Is the problem that you want preallocate the struct array, or that one of the fields in your struct is changing size? Commented Dec 9, 2012 at 21:35
  • @jerad Sorry, I know I could not explain my question exactly. I guess I do not need to preallocate the whole array, only "that one of the fields in your struct is changing size" will be enough. Commented Dec 9, 2012 at 21:42

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.