How do I preallocate memory in a For loop code?
조회 수: 2 (최근 30일)
이전 댓글 표시
How do I preallocate memory for the for loop below? And does preallocating memory makes a simulation run faster?
#1 for Mx = x:50:500;
#2 for My = y:50:400;
#3 %
#4 J1 = [sqrt((Mx-100)^2+(My-20)^2)];
#5 J2 = [sqrt((Mx-20)^2+(My-150)^2)];
#6 J3 = [sqrt((Mx-50)^2+(My-450)^2)];
#7 J4 = [sqrt((Mx-150)^2+(My-450)^2)];
#8 J5 = [sqrt((Mx-7000)^2+(My-200)^2)];
#14 end
#15 end
Thanks
댓글 수: 2
채택된 답변
Stephen23
2015년 5월 4일
편집: Stephen23
2015년 5월 4일
x = 0;
y = 0;
Vx = x:50:500;
Vy = y:50:400;
Cx = [100,20,50,150,7000];
Cy = [20,150,450,450,200];
Tx = bsxfun(@minus,reshape(Vx,1,[],1),Cx(:)).^2;
Ty = bsxfun(@minus,reshape(Vy,1,1,[]),Cy(:)).^2;
out = sqrt(bsxfun(@plus,Tx,Ty));
where the final variable out is arranged with the constants Cx and Cy along the first dimension (rows), then Vx values along the second dimension (columns), and Vy along the third dimension (pages):
>> size(out)
ans =
5 11 9
And to answer your question "does preallocating memory makes a simulation run faster?", then answer is yes! In most cases array preallocation will give much faster code than without array preallocation. MATLAB clearly describes and recommends this in their documentation:
But you don't have to ask here: try it yourself! Make a small experiment with the same operation in a loop and the same one with preallocation... and you will discover the difference yourself.
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
제품
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!