I have two vectors that hold the "start" and "end" locations (as logicals) that I wish to combine as 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 looking 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's a way to accomplish the same exact thing without a for
loop. For example, I could accomplish what I outlined above with the following "hard-coded" statement:
Final([4:8,11:19],1) = 1;
Specifically, is there a way to combine the Start_Locations
and End_Locations
vectors in a way such that I could have a single statement like:
Final(Combined_Start_and_End_Locations,1) = 1;
to accomplish what I did with the for
loop above? I'm trying to learn to avoid for
loops as much as I can and would really appreciate any solution that creates the Final
vector as described above without resorting to a loop.
Problems like this can often be solved using either diff
or cumsum
. They are essentially discrete derivative and integration functions.
For your problem I believe that
Final = cumsum([Starts 0]-[0 Ends]);
Final = Final(1:end-1);
achieves the desired result.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With