Elegant / Vectorized way of getting array from start_index vector and end_index vector?

Hello
Suppose start_index = [1 5 10]; and end_index = [3 8 12];
Is there an elegant solution to get an output of [1 2 3 5 6 7 8 10 11 12], that is the function takes each start value and gives all inclusive values between the start and end value, repeats with the next index, until all inclusive values are included in a single output vector?
Thank you

 채택된 답변

Azzi Abdelmalek
Azzi Abdelmalek 2013년 3월 16일
편집: Azzi Abdelmalek 2013년 3월 16일
EDIT
v=[1 2 3 5 6 7 8 10 11 12]
start_index = [1 5 10];
end_index = [3 8 12];
out=cell2mat(arrayfun(@(x,y) x:y,start_index, end_index,'un',0))
out=intersect(out,v)

댓글 수: 1

Lines 2~4 were what I needed. Brilliant, exactly what I was looking for. Thanks! :)

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Jan
Jan 2013년 3월 16일
편집: Jan 2013년 3월 16일
start_index = [1 5 10];
end_index = [3 8 12];
index(end_index + 1) = -1; % Implicit pre-allocation
index(start_index) = 1;
result = find(cumsum(index));
In many cases logical indexing is more efficient:
result = (cumsum(index(1:end-1)) == 1);
An even more efficient method is FEX: mcolon.

카테고리

도움말 센터File Exchange에서 Startup and Shutdown에 대해 자세히 알아보기

질문:

2013년 3월 16일

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by