Creating vector ranges from variables

I have two vectors that contain the “start” and “end” locations (as logical) that I want to combine to create a third vector, Final :

 Starts = [0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0]; Ends = [0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0]; 

With the final vector, it looks like this:

 Final = [0 0 0 1 1 1 1 1 0 0 1 1 1 1 1 1 1 1 1 0]; 

Currently, I can accomplish this using a for loop as follows:

 Start_Locations = find(Starts); End_Locations = find(Ends); Final = zeros(20,1); for x=1:length(Start_Locations) Final(Start_Locations(x):End_Locations(x),1) = 1; end 

I was wondering if there is a way to do the same without a for loop. For example, I could do what I stated above with the following “hard-coded” statement:

 Final([4:8,11:19],1) = 1; 

In particular, is there a way to combine the Start_Locations and End_Locations so that I can have one statement, for example:

 Final(Combined_Start_and_End_Locations,1) = 1; 

do what i did with the for loop above? I am trying to learn how to avoid for loops as much as possible, and would really appreciate any solution that creates a Final vector, as described above, without resorting to a loop.

+6
source share
1 answer

Problems like this can often be solved with diff or cumsum . They are essentially discrete derivatives and integration functions.

For your problem, I believe that

 Final = cumsum([Starts 0]-[0 Ends]); Final = Final(1:end-1); 

achieves the desired result.

+7
source

Source: https://habr.com/ru/post/975733/


All Articles