Creating a 2D array of ranges from multiple 1D arrays, no for loop

An example best illustrates what i am trying to do:
Let X = 1:100---------(in my application, this is sensor data);
Let Y = [15;45;78]---(this represents specific indexes in the data);
I want to create a 2D array of (separate) Ranges, which go from Y-3 to Y+3.
The command i want to use is: Ranges = X(Y-3:Y+3);
unfortunately, only the first value of Y will be use, therefore this will yield:
Ranges =
12 13 14 15 16 17 18
When I am trying to get:
Ranges =
12 13 14 15 16 17 18
42 43 44 45 46 47 48
75 76 77 78 79 80 81
I am currently using a for loop to get the correct array, but i would like to eliminate it since these operations do not need to happen sequentially and speed is a big issue in this application. If there is a way to do this i'd be very grateful to know.
Thanks

 Accepted Answer

The indices are easy enough to compute without a loop, using bsxfun:
Y = [15;45;78];
IdxRng = bsxfun(@plus, Y, [-3:+3])
IdxRng =
12 13 14 15 16 17 18
42 43 44 45 46 47 48
75 76 77 78 79 80 81
I’m not quite certain what you want to do afterwards, so I’ll leave you with this result.
You can reference ‘IdxRng’ as an array of row vectors to reference your ‘X’ array.

More Answers (1)

For this case, I think, there is not faster then a for loop

Asked:

on 13 Jul 2015

Commented:

on 14 Jul 2015

Community Treasure Hunt

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

Start Hunting!