How to do matrix Preallocation?

1 view (last 30 days)
Hannah on 18 Aug 2021
Edited: Stephen23 on 18 Aug 2021
I have a matrix called 'ResultMtx'. its size is
ans =
792 5
I try to do Preallocation of the matrix by writing:
ResultMtx = zeros(792,5);
Then later in my program I calculate values for the matrix and define it like this:
ResultMtx = [ResultMtx; m, o, r, t, Diff_irr];
ResultMtx = [ResultMtx; nan nan nan nan nan];
But then the result of my matrix is all zeros. what am i doing wrong?

Answers (1)

Stephen23 on 18 Aug 2021
Edited: Stephen23 on 18 Aug 2021
"what am i doing wrong?"
You are concatenating the new data onto the bottom of your preallocated matrix, rather than using indexing to allocate that data to the matrix. You need to use indexing, for example where k is the loop iteration:
ResultMtx(k,:) = [m,o,r,t,Diff_irr];
% ^^^^^ indexing!
ResultMtx(k,:) = NaN;
% ^^^^^ indexing!
This approach is shown in the documentation:

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!