Piece-wise linspace

조회 수: 8 (최근 30일)
Toze
Toze 2012년 1월 30일
Hi
I need to generate a vector (0's and 1's), when I'm given indices for the starting and endpoints of the 1's trains.
Example: m=zeros(1,10); starts=[1 5 9]; ends=[3 6 9];
the generated vector should be [1 1 1 0 1 1 0 0 1 0]
Any way of avoiding a loop? [starts(:):ends(:)] only looks at the first entry of the source vectors...
thanks Tozé

채택된 답변

Jan
Jan 2012년 1월 30일
Do the sections overlap? If not, try this:
m = zeros(1, 10);
starts = [1 5 9];
ends = [3 6 9];
m(starts) = 1;
m(ends) = -1;
m = cumsum(m);
If they sections are overlapping:
m = zeros(1, 10);
p = zeros(1, 10);
starts = [1 5 9];
ends = [3 6 9];
m(starts) = 1;
m(ends) = -1;
m = cumsum(m);
p(m > 0) = 1;
I cannot test this currently, so please keep care.
And perhaps this helps: FEX: interval merging.

추가 답변 (3개)

Bjorn Gustavsson
Bjorn Gustavsson 2012년 1월 30일
Why bother searching for a cunning loop-free version (non-explicit) when the looped version is so straightforward? How much time does it take to come up with something clever compared to the potential gain in run-time?
HTH,

Toze
Toze 2012년 1월 30일
Hi HTH I have aprox. 10^10 elements in each run... Tozé

Toze
Toze 2012년 1월 30일
Hi Jan
With one minor change (m(ends) should be m(ends+1)), this is exactly what I was looking for .. a clever solution.

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by