从开始/结束索引列表创建矢量化数组

mer*_*erv 11 matlab vectorization

我有一个双列矩阵M,包含一堆间隔的开始/结束索引:

startInd   EndInd
1          3
6          10
12         12
15         16
Run Code Online (Sandbox Code Playgroud)

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

v = [1 2 3 6 7 8 9 10 12 15 16];
Run Code Online (Sandbox Code Playgroud)

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

v = [];
for i=1:size(M,1)
    v = [v M(i,1):M(i,2)];
end
Run Code Online (Sandbox Code Playgroud)

gno*_*ice 9

这是我喜欢用于此特定问题的矢量化解决方案,使用以下函数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
Run Code Online (Sandbox Code Playgroud)


Mat*_*ter 6

cell2mat(arrayfun(@colon,M(:,1)',M(:,2)','UniformOutput',false))
Run Code Online (Sandbox Code Playgroud)

我没有IMFILL,但在我的机器上这种方法比其他建议更快,我认为由于使用了find,它会超过IMFILL方法.

如果M被设置为转置(并且我们调整arrayfun的第三和第四个参数),它可以更快.