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
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 .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.