如何重写多个用于在MATLAB速度优化循环?

问题描述 投票:0回答:1

我希望我的代码运行速度更快,这部分似乎是它使得代码的运行速度较慢。

我试图向量化它,并使用meshgrid,但不能弄明白。

%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]其中ijk是节点的数组,并且在阵列的每一行它们不彼此相等。

它增加了一个[i j k]组合combinations_withpackets如果有来自节点ij和节点ik

matlab performance vectorization
1个回答
2
投票

如果我创建一个随机矩阵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

它应该比路快for循环的解决方案。

该算法产生(N-2)*(N-1)*(N)组合(如由安德Biguri解释的,它几乎是O(N ^ 3)),所以对于大ñ它会消耗大量的内存。

© www.soinside.com 2019 - 2024. All rights reserved.