Tak
Tak

Reputation: 3616

Vector elements are indices of another vector Matlab

I have 1x10 vector A

A = [11 22 33 44 55 66 77 88 99 111]

Each value in A represents an index in vector B which is 1x200.

I want to get each value in vector A and go to the index of this value in vector B and get the value of this index and the 10 items before and 10 items after.

For example, the first element in vector A is 11, so I'll go to index 11 in vector B and get the value of this index (11th value) and the value of the 10 items before it (from 1 to 10) and 10 items after (from 12 to 21), same for every element in A.

Is possible to do it without loops?

Upvotes: 0

Views: 132

Answers (2)

Mohsen Nosratinia
Mohsen Nosratinia

Reputation: 9864

Here is on using bsxfun

R = B(bsxfun(@plus, A(:), -10:10));

now row n in R contains the elements corresponding to element n in A. If you want it in a vector use:

R = reshape(B(bsxfun(@plus, A(:), -10:10)), 1, []);

Upvotes: 2

Prashant Kumar
Prashant Kumar

Reputation: 22539

The straight-forward way, with the loop. How fast do you need it? Is a simple loop approach not fast enough?

C = zeros(21, length(A))
for k = 1:length(A)
    C(:,k) = (-10:10)' + A(k);
end
C = C(:);

B(C)    # returns the elements you seek

Upvotes: 0

Related Questions