0

I would like to vectorize the following Octave code:

A = 1:100;
B = [20 40 60];
C = zeros(3,11);

for i = B,
    C(i,:) = A( (B(i) - 10) : B(i) );
end

Which extracts sub-arrays starting at specific indexes from a longer array.

I tried:

C = A(B - 10,B);

But this only returns the first sub-array.

Thanks

Shai
  • 111,146
  • 38
  • 238
  • 371
Tom
  • 6,601
  • 12
  • 40
  • 48

1 Answers1

1

How about

>> C = A( bsxfun( @plus, -10:0, B' ) );

C =

    10    11    12    13    14    15    16    17    18    19    20
    30    31    32    33    34    35    36    37    38    39    40
    50    51    52    53    54    55    56    57    58    59    60

If you don't have bsxfun in octave, you can do this with repmat

C = A( repmat( -10:0, [3 1] ) + repmat( B', [1 11] ) ); 

PS,
It is best not to use i as a variable in Matlab.

Community
  • 1
  • 1
Shai
  • 111,146
  • 38
  • 238
  • 371