【问题标题】:Vectorization of Conditions( inside Loop)条件向量化(循环内)
【发布时间】:2018-12-16 20:52:59
【问题描述】:

为了更快的实现,我想在matlab代码下面进行矢量化:

   A=randi([0 1],20,20);
    B=zeros(20);
    for row = 5:15
     for column = 5:15
    if(A(row,column)==1 && (A(row+1,column)~=1 ||A(row,column+1)~=1)) 
      B(row,column)=1;
    end
     end
    end

我该怎么做?

【问题讨论】:

    标签: matlab performance for-loop if-statement vectorization


    【解决方案1】:

    只需计算整个循环的所有A(row, column)==1 等,然后使用普通的布尔运算。对于您提出的情况,这应该可以正常工作(尽管短路的东西的操作方式略有不同,因此这可能并不总是可行)。

    row = 5:15;
    col = 5:15;
    firstCond = A(row, col) == 1;
    secondCond = A(row+1, col) ~= 1;
    thirdCond = A(row, col+1) ~= 1;
    allCond = firstCond & (secondCond | thirdCond);
    B(row, col) = double(allCond);
    

    【讨论】:

    • 投了赞成票,但是这个版本的矢量化并没有加快多少! ...平均 3 mili sec :) ...比 amahmud 的版本慢一点(见吹或起来)...
    【解决方案2】:

    我希望这个对你有用。

    A=randi([0 1],20,20);    
    B=zeros(20);    
    z = find(A(5:15,5:15) == 1 & (A(6:16,5:15)~=1 | A(5:15,6:16)~=1));    
    y = B(5:15,5:15);    
    y(z) = 1;    
    B(5:15,5:15) = y;  
    

    【讨论】:

    • 投了赞成票并选择了答案,但是您的矢量化版本并没有加快多少! ...平均 3 英里秒 :)
    • 现在您只使用 20*20 矩阵,原始情况下的总时间约为 0.003 秒,非常低。我认为大型矩阵的加速过程会更加明显。
    • 我认为@Zizy Archer 的版本也很有用,如果你只是在一行中添加所有的逻辑表达式。你也可以看看这个,A=randi([0 1],20,20); B=零(20);行 = 5:15;科尔= 5:15; allCond = (A(row, col) == 1) &((A(row+1, col) ~= 1) | (A(row, col+1) ~= 1)); B(row, col) = double(allCond);
    • 不,不是,我跑了 20000 次,平均差异(循环和 zizy 的版本之间)是 0.0008.. 顺便说一句,我尝试将 find 直接替换为 y() 而不使用 z.. . 没有变得更快....
    猜你喜欢
    • 2017-08-01
    • 2021-11-13
    • 1970-01-01
    • 1970-01-01
    • 2017-05-26
    • 2020-10-20
    • 2011-07-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多