arrays - 如何比较和添加数组的元素
问题描述
我想取一个数组让我们说 3x5 如下
1 3 5
1 3 5
2 8 6
4 5 7
4 5 8
并编写一个代码来创建一个新数组,如果第一列和第二列中的数字等于其下一行中的数字,则该数组将第三列与前一个数字相加。
由于第 1 行和第 2 行中的前两个值,则将第 1 行和第 2 行中的第三个元素相加
所以上面数组的输出应该是这样的
1 3 10
2 8 6
4 5 15
解决方案
该函数accumarray(subs,val)
使用下标 subs 来累积向量 val 的元素。所以我们可以使用这个函数对第一列和第二列中具有相同值的第三列中的元素求和。我们可以用unique(...,'rows')
它来确定哪些值对是唯一的。
%Example data
A = [1 3 5,
1 3 5,
2 3 6,
4 5 7,
4 5 7]
%Get the unique pair of value based on the first two column (uni) and the associated index.
[uni,~,sub] = unique(A(:,1:2),'rows');
%Create the result using accumarray.
R = [uni, accumarray(sub,A(:,3))]
如果订单很重要,那么脚本会稍微复杂一点:
%Get the unique pair of value based on the first two column (uni) and the associated index.
[uni,~,sub] = unique(A(:,1:2),'rows');
%Locate the consecutive similar row with this small tricks
dsub = diff([0;sub])~=0;
%Create the adjusted index
subo = cumsum(dsub);
%Create the new array
R = [uni(sub(dsub),:), accumarray(subo,A(:,3))]
或者您可以使用 for 循环获得相同的结果:
R = A(1,:)
for ii = 2:length(A)
if all(A(ii-1,1:2)==A(ii,1:2))
R(end,3) = R(end,3)+A(ii,3)
else
R(end+1,:) = A(ii,:)
end
end
基准:
100000x3
在 mathworks 实时编辑器上有一个大小为 A 的数组:
for 循环大约需要5.5s
(没有预分配,所以它很慢)
矢量化方法大约需要0.012s
推荐阅读
- java - 无法获取上传图像到 Firebase android 的下载 URL
- sql - 如何在 SQL 中遍历表的子集
- python - 如何在 DAG (pandas\networkx) 上获取所有连接边的链
- eclipse - Windows 上的 OMNeT++ 5.5.1 和 SimuLTE - 调试错误
- java - 如何为 Android Studio 中的 imageView 分配整数值?
- ios - iOS NSURLErrorDomain Code=-1200 “发生 SSL 错误,无法与服务器建立安全连接。”
- android - Emulate NDEF Tag in ReactNative for Android
- c++ - C++:对不存在的命名空间使用命名空间指令
- c# - 如何处理 OWIN 应用程序的 web.config 更改
- windows - 用于在资源管理器中双击文件并在 Windows 终端中使用 WSL 应用程序(Neovim、Vim 等)启动/运行它的脚本