# How to do matrix Preallocation?

조회 수: 2 (최근 30일)
Hannah . 2021년 8월 18일
편집: Stephen23 . 2021년 8월 18일
I have a matrix called 'ResultMtx'. its size is
size(ResultMtx)
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];
end
ResultMtx = [ResultMtx; nan nan nan nan nan];
But then the result of my matrix is all zeros. what am i doing wrong?

댓글을 달려면 로그인하십시오.

### 답변 (1개)

Stephen23 2021년 8월 18일
편집: Stephen23 님. 2021년 8월 18일
"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!
or
ResultMtx(k,:) = NaN;
% ^^^^^ indexing!
This approach is shown in the documentation:

댓글을 달려면 로그인하십시오.

### 카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

### Community Treasure Hunt

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

Start Hunting!