在MATLAB中分割阵列 [英] Split an array in MATLAB

查看:143
本文介绍了在MATLAB中分割阵列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个整数数组,我想将该数组拆分为0的地方,并提供一个给我拆分点的函数.

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.

示例:数组: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

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.

推荐答案

这是使用功能 DIFF 查找:

>> 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];  %# Sample array
>> edgeArray = diff([0; (array(:) ~= 0); 0]);
>> indices = [find(edgeArray > 0)-1 find(edgeArray < 0)]

indices =

     3    10
    14    20
    22    25

以上代码的工作方式是首先创建一个带有一个表示非零元素的列数组,然后用零填充该数组(以防任何非零跨度扩展到数组边缘),并采用逐元素差异.这给出了向量edgeArray,其中1指示非零跨度的开始,而-1指示非零跨度的结束.然后,函数 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 with 1 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.

一个旁注/nitpick:这些不是您所说的非零跨度的开始和结束的索引.从技术上讲,它们是非零跨度的开始位置 和结束时间 的索引.您可能实际上想要以下内容:

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:

>> indices = [find(edgeArray > 0) find(edgeArray < 0)-1]

indices =

     4     9
    15    19
    23    24

这篇关于在MATLAB中分割阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆