[英]speed up loop in matlab
I'm very new in MATLAB (this is my first script).我是 MATLAB 的新手(这是我的第一个脚本)。 I wonder how may I speed up this loop, I don't know any toolbox or 'tricks' as I'm a newbie on it.我想知道如何加快这个循环,我不知道任何工具箱或“技巧”,因为我是新手。 I tried to code it with instinct, it works, but it is really long.我试图用直觉对其进行编码,它有效,但它真的很长。
All are variables get with fread
or integer
manually entered, so this is basically simple math, but I have no clue on why is it so long (maybe nested loops?) and how to improve, as I am more familiar with Python and for example multiprocess
.所有变量都是用fread
或integer
手动输入的,所以这基本上是简单的数学运算,但我不知道为什么这么长(可能是嵌套循环?)以及如何改进,因为我更熟悉 Python 和例如multiprocess
。
Thanks a lot非常感谢
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
You have one issue with the given code.您对给定的代码有一个问题。 The blow line:打击线:
Points = [Points; X, Y, distance(i,j)];
This will definitely slow up your code.这肯定会减慢您的代码。 You need to initialize this array to store the numbers.您需要初始化此数组以存储数字。 If you initialize it, you will find good difference in speed.如果你初始化它,你会发现速度上有很好的差异。
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
Note that, you code only saves the last value of X, is this what you want?请注意,您的代码仅保存 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
try using parallelization- "parfor" instead of "for" that uses all available processors.尝试使用并行化-“parfor”而不是使用所有可用处理器的“for”。
parfor i=1:nbLines
rest of code here
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.