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

 Réponse acceptée

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.

2 commentaires

This is exactly what i was looking for, thanks.
My pleasure!

Connectez-vous pour commenter.

Plus de réponses (1)

Azzi Abdelmalek
Azzi Abdelmalek le 13 Juil 2015
For this case, I think, there is not faster then a for loop

Community Treasure Hunt

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

Start Hunting!

Translated by