gpt4 book ai didi

arrays - 基于重复字符位置创建数组的最简单方法

转载 作者:太空宇宙 更新时间:2023-11-03 20:26:21 25 4
gpt4 key购买 nike

我想使用数组中的重复段对我的元素进行分组。中断基本上取决于重复段的位置,在我的真实数据中包含约 10000 个元素,我想知道是否有更简单的方法来做到这一点。

这里是一个简短的例子来阐明我想要什么:

假设我有一个数组,

A=[1 5 3 4 4 4 6 9 8 8 9 5 2];

我想要的是将 A 分解为 [1 5 3]、[6 9] 和 [9 5 2];

使用 matlab 编写此代码最简单的是什么?

谢谢。

最佳答案

对于矢量化解决方案,您可以找出与邻居的前向或后向差异为零的位置,然后使用 bwlabel(来自图像处理工具箱)和 accumarray 收集数据。

A=[1 5 3 4 4 4 6 9 8 8 9 5 2];

d = diff(A)==0;
%# combine forward and backward difference
%# and invert to identify non-repeating elments
goodIdx = ~([d,false]|[false,d]);

%# create list of group labels using bwlabel
groupIdx = bwlabel(goodIdx);

%# distribute the data into cell arrays
%# note that the first to inputs should be n-by-1
B = accumarray(groupIdx(goodIdx)',A(goodIdx)',[],@(x){x})

编辑

如果您希望重复元素也出现在元胞数组中,请将最后两行代码替换为以下代码

 groupIdx = cumsum([1,abs(diff(goodIdx))]);
B = accumarray(groupIdx',A',[],@(x){x})

EDIT2

如果你也想拆分相同数字的连续组,你需要按如下方式计算groupIdx:

 groupIdx = cumsum([1,abs(diff(goodIdx))|~d.*~goodIdx(2:end)])

关于arrays - 基于重复字符位置创建数组的最简单方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12077503/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com