# How to avoid this problem "consider preallocating the memory .for speed" in the below sample code

조회 수: 3(최근 30일)
댓글: Steven Lord 2017년 9월 14일
The code is like this
m = [];
x=[100,200,300.....]
for k= 1:1:142
if(k >= 142)
break;
end
%
if x(k)== [5];
mm = horzcat(mm,xx);
elseif (x(k+1) >= 20)
bb = 10- lj1 ;
cc = dec2bin(bb,3)-'0';
mm = horzcat(mm,cc);
%
elseif (x(k+2) >= 10)
cc = dec2bin(bb,3)-'0';
mm = horzcat(mm,cc);
%
end
end
how the preallocation of 'mm' can be done to increase the speed of execution. Kindly suggest
##### 댓글 수: 3표시 이전 댓글 수: 2숨기기 이전 댓글 수: 2
Steven Lord 2017년 9월 14일
Can you explain the purpose of your code in words? If we know the underlying problem you're trying to solve, we may be able to suggest an alternative approach that avoids growing memory each time through the loop (potentially by avoiding the loop entirely!)

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

### 답변(2개)

Stalin Samuel 2017년 9월 14일
Refer the below url which has example of Preallocation
##### 댓글 수: 0표시 이전 댓글 수: -1숨기기 이전 댓글 수: -1

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

KSSV 2017년 9월 14일
If you are aware of the dimensions of the allocation preallcoate it using:
x = zeros(m,n) ;
If you are not aware of dimensions, and you know that it is either a row or a column vector:
x = zeros([],n) ; % a row row vector
x = zeros(m,[]) ; % a column vector
If you are not sure of dimensions, allocate it as cell:
x = cell([],n) ;
x = cell(m,[]) ;

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

### 범주

Find more on Modify Image Colors in Help Center and File Exchange

### Community Treasure Hunt

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

Start Hunting!

Translated by