matlab - 如何在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
,并且在数组的每一行它们彼此不相等。j
k
如果有来自 node to和 node to的数据包,它会添加一个[i j k]
组合。combinations_withpackets
i
j
i
k
解决方案
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.
推荐阅读
- php - 一个字符串响应中的 Ajax 多个文件名
- angular - 发送带有角度查询参数的帖子时出错
- docker - 无人机 CI - docker 插件 - 解析错误。为什么无人机无法解析?
- ffmpeg - FFMPEG 图像序列正常并反转为单个视频
- arduino - Mega R3 WiFi:ESP8266 模块代码中串行通信的初始化问题
- css - 页面加载时可变字体闪烁
- javascript - react-native-fs 库没有移动或复制文件 - 奇怪的结果
- vba - VBA:使用数组公式
- quaternions - 如何找到两个 IMU 测量值之间的转换?
- react-native - React Native将文件上传到multer,我得到空缓冲区