Grabbing sections of a matrix by using two doubles as the index

1 view (last 30 days)
Hello everyone,
I am trying to access sections of an array such as:
data = [10 10.5 11.5 13 15 16 20.5 24];
by using the following two arrays:
indStart = [1 0 0 0 1 0 0 0]; indEnd = [0 0 1 0 0 0 0 1];
The final output should look something like this:
result = { [10 1.5 11.5] }
{ [15 16 20.5 24] }
This is what i have tried, along with little variations of it:
result{ : } = data(indStart : indEnd);
The results of my method is either an error, or i can access 1:3, but not get 5:8.
I know i can do this quite easily with a for loop, but i am trying to accomplish this using indexing and logical statements so that processing time stays down. The final script needs to be processed by ga(), so any cut down on processing time is very valuable.
Thank you to anyone who can help!

Accepted Answer

James Tursa
James Tursa on 23 Dec 2019
Edited: James Tursa on 23 Dec 2019
E.g.,
result = arrayfun(@(x1,x2)data(x1:x2),find(indStart),find(indEnd),'uni',false);
This assumes of course that the indStart and indEnd are consistent and have the appropriate number of 1's etc.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!