Question

I have the array

a=1:20

and a series of indices which indicate where I want to start pulling data out:

i=[4,12]

For each index i, I want that index and the next four (well, x, really) elements in a column or row. I'll avoid getting to close to the end of the array, so that special case can be disregarded.

If I was hard-coding this, I could use:

a([4:8;12:16])

and this would achieve my result.

But i may have many different values.

Any thoughts on how I can transform a list of indices into a matrix of ranges, or other ways to solve this problem?

EDIT I am using Matlab 2007; it would be preferable if the solution relied solely on Matlab's internals and toolboxes. bsxfun is not present until 2007a.

Was it helpful?

Solution

Let i be your indicesx and x the number of elements you want in addition to the elements in i, then you can use

i = [4 6 8];
x = 4; 

bsxfun(@plus, 0:x, i(:)) 

to get a matrix of indices:

ans =

     4     5     6     7     8
     6     7     8     9    10
     8     9    10    11    12

If you do not have access to bsxfun you can use repmat instead:

i = [4 6 8];
x = 4; 

repmat(i(:), 1, x+1) + repmat(0:x, length(i), 1)

OTHER TIPS

Here is a solution without bsxfun but with repmat inspired by the previous answer.

i = [4 6 8];
x = 4;
p = repmat(1:x,length(i),1);
q = repmat(i',1,x);
p+q
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top