matlab - 如何在不使用 for 循环的情况下对不同大小的矩阵的各个部分求和?
问题描述
我有一个相对较大的矩阵 NxN (N~20,000) 和一个 Nx1 向量,用于标识必须组合在一起的索引。
我想将矩阵的各个部分相加,原则上可以有不同数量的元素和不相邻的元素。我很快写了一个可以正常工作的双 for 循环,但它当然效率低下。分析器将这些循环识别为我的代码中的瓶颈之一。
我试图找到一种智能矢量化方法来解决这个问题。我探索了arrayfun
、cellfun
和bsxfun
函数,并寻找类似问题的解决方案……但我还没有找到最终解决方案。
这是带有两个 for 循环的测试代码:
M=rand(10); % test matrix
idxM=[1 2 2 3 4 4 4 1 4 2]; % each element indicates to which group each row/column of M belongs
nT=size(M,1);
sumM=zeros(max(idxM),max(idxM));
for t1=1:nT
for t2=1:nT
sumM(t1,t2) = sum(sum(M(idxM==t1,idxM==t2)));
end
end
解决方案
您可以accumarray
按如下方式使用:
nT = size(M,1); % or nT = max(idxM)
ind = bsxfun(@plus, idxM(:), (idxM(:).'-1)*nT); % create linear indices for grouping
sumM = accumarray(ind(:), M(:), [nT^2 1]); % compute sum of each group
sumM = reshape(sumM, [nT nT]); % reshape obtain the final result
推荐阅读
- sorting - 在 Arm 装配中实现选择排序时遇到问题
- html - 替换 Bootstap svg 占位符图像
- angular - 每当单击该表值时,Angular/PrimeNG 都会在索引/值处打开一个模式对话框
- mysql - 将 CIDR 格式的 IPv6 范围转换为 MySQL 中的 IPv6 地址范围(开始和结束 ips)
- reactjs - 为什么从 redux-toolkit 更新 entityAdapter 选择器中的一个元素后重新渲染整个列表?
- javascript - 一键无限循环
- reactjs - 登录不持久 - Netlify 前端和 Heroku 后端
- python - 如何在python中使用gensim获取相关匹配词?
- angular - 无法 dockerize Angular 应用程序 - sh:ng-openapi-gen:未找到
- sorting - Array.sort ( (a,b) => a - b)