Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
671 views
in Technique[技术] by (71.8m points)

matlab - vectorized array creation from a list of start/end indices

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...