MATLAB Answers

0

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

aditya sahu 님이 질문을 제출함. 14 Sep 2017
최근 활동 Steven Lord 님이 댓글을 추가함. 14 Sep 2017
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

Code is not correct...copy the correct code.
SIR @KSSV This is the right code(piece of sample code from the large code)...and the issue is to preallocate the value of 'mm'. As the loop is very large IN THE ORIGINAL CODE 2 problems are coming 1. is it is killing a lot time for executing 2. memory problem...
dd=imread('x.bmp');
qq=reshape(dd',[100],[])';
qq=double(qq);
qq=qq';
ss=dec2bin(qq)-'0';
ss=ss';
pp=dec2bin(qq)-'0';
xx = [];
bb = [];
cc = [];
mm = [];
lb = [ 0 21 31];
ub = [ 20 30 41];
for k=1:3:105
if(numel(mm) >= 2345)
break;
end
if(k >= 100)
break;
end
xx = pp((k+1),6:8);
mm = horzcat(mm,xx);
stdif1 = abs(qq(k) - qq(k+1));
stdif2 = abs(qq(k+2) - qq(k+1));
if (stdif1 >= lb(1)) && ( stdif1 <= ub(1))
lj1 = lb(1);
bb = stdif1 - lj1 ;
cc = dec2bin(bb,3)-'0';
mm = horzcat(mm,cc);
elseif(stdif1 >= lb(2)) && ( stdif1 <= ub(2))
lj1 = lb(2);
bb = stdif1 - lj1 ;
cc = dec2bin(bb,3)-'0';
mm = horzcat(mm,cc);
else(stdif1 >= lb(3)) && ( stdif1 <= ub(3))
lj1 = lb(3);
bb = stdif1 - lj1 ;
cc = dec2bin(bb,3)-'0';
mm = horzcat(mm,cc);
end
end
mm=reshape(mm,3,[])';
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!)

로그인 to comment.

답변 수: 2

Answer by Stalin Samuel on 14 Sep 2017

Refer the below url which has example of Preallocation
  1. pre-allocate memory when using MATLAB
  2. Preallocation

  댓글 수: 0

로그인 to comment.


Answer by KSSV
on 14 Sep 2017

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,[]) ;

  댓글 수: 0

로그인 to comment.



Translated by