在 MATLAB 中拆分数组
我有一个整数数组,我想在 0 出现的地方分割这个数组,并有一个函数给我分割点。
示例: Array : 0 0 0 1 2 4 5 6 6 0 0 0 0 0 22 4 5 6 6 0 0 0 4 4 0
该函数必须返回这些数字:
[ 3 10 ;14 20 ;22 25 ]
这些数字是非零数字的开始和结束索引。
I have an array of integer numbers, and I want to split this array where 0 comes and a function that give me points of split.
Example: Array : 0 0 0 1 2 4 5 6 6 0 0 0 0 0 22 4 5 6 6 0 0 0 4 4 0
The function must return these numbers:
[ 3 10 ;14 20 ;22 25 ]
These numbers are index of start and end of nonzero numbers.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是使用函数 DIFF 和 FIND:
上面的代码首先创建一个列数组,其中的元素指示非零元素,填充这个数组零(如果任何非零跨度延伸到数组边缘),并取元素差异。这给出了一个向量
edgeArray
,其中1
表示非零跨度的开始,-1
表示非零跨度的结束。然后函数 FIND 用于获取开始和结束的索引。旁注/挑剔:这些不是像您所说的非零跨度的开始和结束的索引。从技术上讲,它们是非零跨度开始之前和结束之后的索引。您可能实际上想要以下内容:
Here's a simple vectorized solution using the functions DIFF and FIND:
The above code works by first creating a column array with ones indicating non-zero elements, padding this array with zeroes (in case any of the non-zero spans extend to the array edges), and taking the element-wise differences. This gives a vector
edgeArray
with1
indicating the start of a non-zero span and-1
indicating the end of a non-zero span. Then the function FIND is used to get the indices of the starts and ends.One side note/nitpick: these aren't the indices of the starts and ends of the non-zero spans like you say. They are technically the indices just before the starts and just after the ends of the non-zero spans. You may actually want the following instead:
试试这个
Try this
关于主题,但略有不同:
正如 gnovice 已经指出的与索引相关的位置语义,我将补充一点,通过此解决方案,各种方案在计算
指数
时,可以以非常简单的方式处理。因此,对于您的要求:On the theme, but with a slight variation:
As
gnovice
already pointed out on the positional semantics related toindices
, I'll just add that, with this solution, various schemes can be handled very straightforward manner, when calculatingindices
. Thus, for your request: