从开始/结束索引列表创建矢量化数组 [英] vectorized array creation from a list of start/end indices

查看:32
本文介绍了从开始/结束索引列表创建矢量化数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个两列矩阵 M ,其中包含一组区间的开始/结束索引:

I have a two-column matrix M that contains the start/end indices of a bunch of intervals:

startInd   EndInd
1          3
6          10
12         12
15         16

如何生成所有区间索引的向量:

How can I generate a vector of all the interval indices:

v = [1 2 3 6 7 8 9 10 12 15 16];

我正在使用循环执行上述操作,但我想知道是否有更优雅的矢量化解决方案?

I'm doing the above using loops, but I'm wondering if there's a more elegant vectorized solution?

v = [];
for i=1:size(M,1)
    v = [v M(i,1):M(i,2)];
end

推荐答案

这是我喜欢用于这个特定问题的矢量化解决方案,使用函数 cumsum:

Here's a vectorized solution I like to use for this particular problem, using the function cumsum:

v = zeros(1, max(endInd)+1);  % An array of zeroes
v(startInd) = 1;              % Place 1 at the starts of the intervals
v(endInd+1) = v(endInd+1)-1;  % Add -1 one index after the ends of the intervals
v = find(cumsum(v));          % Perform a cumulative sum and find the nonzero entries

这篇关于从开始/结束索引列表创建矢量化数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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