【问题标题】:speed up loop in matlab在matlab中加速循环
【发布时间】:2021-06-14 18:50:34
【问题描述】:

我是 MATLAB 的新手(这是我的第一个脚本)。 我想知道如何加快这个循环,我不知道任何工具箱或“技巧”,因为我是新手。我试着用直觉来编码,它有效,但它真的很长。

所有变量都是用freadinteger 手动输入的,所以这基本上是简单的数学运算,但我不知道为什么这么长(可能是嵌套循环?)以及如何改进,就像我一样更熟悉 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

【问题讨论】:

标签: performance matlab for-loop


【解决方案1】:
    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

【讨论】:

  • 我得到 '|| 的操作数和 && 运算符必须可转换为逻辑标量值。对于这一行: id = find(lidarDate(i)>posDate && lidarDate(i)
  • 使用 & 代替 &&
  • 是的,对不起,我意识到得太晚了。再次感谢,最后一件事(我发誓,你太善良了)。在循环结束时,我运行“ptCloud = pointCloud(Points)”,但它告诉我“Points”的值无效,预期输入是以下类型之一:单、双,而不是它的类型是单元格。
  • 是的....现在点是单元格数组。您可以使用花括号访问它们或使用函数 cell2mat 将其转换为矩阵。
【解决方案2】:

您对给定的代码有一个问题。吹线:

 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 的最后一个值,这是你想要的吗?

【讨论】:

  • 非常感谢!它确实运行得更快,这很明显,但是当 nbLines[i] 大约为 1500 时,它又开始变慢(注意:len(nbLines) 大约为 4000)。有没有最后的技巧来结束它?也许并行化?
  • 您可以通过在完整数组中使用逻辑索引来避免内部两个循环。检查答案...如果抛出任何错误,您需要检查尺寸。
【解决方案3】:

尝试使用并行化——使用所有可用处理器的“parfor”而不是“for”。

parfor i=1:nbLines
   rest of code here
end

【讨论】:

    猜你喜欢
    • 2016-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-17
    • 2016-08-10
    • 2016-04-14
    相关资源
    最近更新 更多