[英]speed up loop in matlab
我是 MATLAB 的新手(這是我的第一個腳本)。 我想知道如何加快這個循環,我不知道任何工具箱或“技巧”,因為我是新手。 我試圖用直覺對其進行編碼,它有效,但它真的很長。
所有變量都是用fread
或integer
手動輸入的,所以這基本上是簡單的數學運算,但我不知道為什么這么長(可能是嵌套循環?)以及如何改進,因為我更熟悉 Python 和例如multiprocess
。
非常感謝
X = 0;
Points = [0,0,0];
for i=1:nbLines
for j=1:nbPositions-1
if lDate(i)>posDate(j) && lDate(i)<=posDate(j+1)
weight = (lDate(i) - posDate(j)) / (posDate(j+1)- posDate(j));
X = posX(j)*(1-weight) + posX(j+1) * weight;
end
end
if X ~= 0
for j=1:nbScans
Y = - distance(i,j) / tan(angle(i,j));
Points = [Points;X, Y, distance(i,j)];
end
end
end
您對給定的代碼有一個問題。 打擊線:
Points = [Points; X, Y, distance(i,j)];
這肯定會減慢您的代碼。 您需要初始化此數組以存儲數字。 如果你初始化它,你會發現速度上有很好的差異。
X = 0;
Points = zeros([],3) ;
Points(1,:) = [0,0,0];
count = 1 ;
for i=1:nbLines
for j=1:nbPositions-1
if lDate(i)>posDate(j) && lDate(i)<=posDate(j+1)
weight = (lDate(i) - posDate(j)) / (posDate(j+1)- posDate(j));
X = posX(j)*(1-weight) + posX(j+1) * weight;
end
end
if X ~= 0
for j=1:nbScans
count = count+1 ;
Y = - distance(i,j) / tan(angle(i,j));
Points(count,:) = [X, Y, distance(i,j)];
end
end
end
請注意,您的代碼僅保存 X 的最后一個值,這是您想要的嗎?
X = 0;
Points = cell([],1) ;
Points{1} = [0,0,0];
count = 1 ;
for i=1:nbLines
id = find(lDate(i)>posDate & lDate(i)<=posDate) ;
if length(id) > 1
weight = (lDate(i) - posDate(id(1))) / (posDate(id(end))- posDate(id(1)));
X = posX(id(1))*(1-weight) + posX(id(end)) * weight;
end
if X ~= 0
j=1:nbScans ;
count = count+1 ;
Y = - distance(i,j)./tan(angle(i,j));
Points{count} = [repelem(X,size(Y,2),size(Y),1), Y, distance(i,j)'];
end
end
嘗試使用並行化-“parfor”而不是使用所有可用處理器的“for”。
parfor i=1:nbLines
rest of code here
end
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.