Preallocating for speed?
이전 댓글 표시

Hello. The variables that I indicate with the red arrow, how do I modify the speed? what function in matlab is it?
답변 (1개)
When you append data to a variable like this:
a=[1 2 3];
a=[a 4];
Matlab first allocates a block of memory large enough to hold 4 numbers, then it copies the data from the first array to the second array, then writes the new element to that new array. After that the memory for the first array is released.
If you do this often, that means you're copying a lot of data around, which takes time. What you can do instead is to create an array before you start the loop. This array is large enough to hold most or all the data you expect to encounter.
a=zeros(1,4);
for n=1:4
a(n)=n;
end
a
This allocates memory only once and removes the need of copying the data over and over again. Because you do this before using it, this strategy is called pre-allocation.
You can also use this strategy if you don't know the expected number of elements:
a=zeros(1,4);
n=0;
while rand<0.75
n=n+1;
a(n)=n;
end
% remove unused elements
% this will not do anything if n>=numel(a)
a((n+1):end)=[];
a
카테고리
도움말 센터 및 File Exchange에서 Logical에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!