首页 > 解决方案 > 如何在matlab中重写多个for循环以优化速度?

问题描述

我希望我的代码运行得更快,这部分似乎让代码运行得更慢。

我试图对其进行矢量化并使用网格网格,但无法弄清楚。

%generate all noma node combinations with packets
combinations_withpackets=[];
for i=1:N
    for j=1:N
        if(i~=j)
           for k=1:N
               if((k~=i)&&(k~=j))
                   if((packets(i,j)>0)&&(packets(i,k)>0))   
                       combinations_withpackets=[combinations_withpackets;i j k];
                   end
               end
           end
        end
    end
end

这应该创建一个形式为[i j k]where和是节点的数组i,并且在数组的每一行它们彼此不相等。jk

如果有来自 node to和 node to的数据包,它会添加一个[i j k]组合。combinations_withpacketsijik

标签: matlabperformancevectorization

解决方案


If I create a random matrix packets:

N       = 50                %size of the packets matrice
packets = round(rand(N,N)); %random matrice
comb    = nchoosek(1:N,3);  %all combination without permutation
combrow = perms(1:3);       %permutation for dimension 3
comb    = reshape(comb(:,combrow),[],3); %all combination with permutation
f1      = find(packets(sub2ind([N,N],comb(:,1),comb(:,2)))>0); %check condition 1
f2      = find(packets(sub2ind([N,N],comb(:,1),comb(:,3)))>0); %check condition 2
ind     = ismember(f1,f2); %check condition 1&&2
cwp     = comb(f1(ind),:);   %get the result

It should be way faster than the for loop solution.

This algorithm produce (N-2)*(N-1)*(N) combinations (as explained by Ander Biguri, it's almost O(N^3)), so for big N it will consume a lot of memory.


推荐阅读