필터 지우기
필터 지우기

Matlab arrays preallocation techniques

조회 수: 2 (최근 30일)
Giovanni Gardan
Giovanni Gardan 2020년 5월 25일
댓글: Stephen23 2020년 5월 25일
I'm trying to make my code faster to run. In literature, one of technique is preallocating arrays used in the code.
Let's suppose we have a 1000x1000 matrix to pre-allocate before a while loop. It is known that sparse form save memory, but save also time?
Which of the following two options is better?
%First way
A = zeros(1000);
%Second way
A = sparse(1000);
  댓글 수: 3
Giovanni Gardan
Giovanni Gardan 2020년 5월 25일
Thank you for the answer.
Yes you are right, but seems like in some cases the first way is faster, in other cases the secondo way is faster. I'd like to know if there is a general rule to treat preallocation
Stephen23
Stephen23 2020년 5월 25일
In general adding new data to sparse arrays is slow. Rather than preallocating the entire sparse array the usual efficient approach is to build up vectors of the indices and the data in the loop and after the loop convert them to sparse.
Your array is not very large I doubt that there is much point in defining it as sparse anyway.

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

답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by