Tak
Tak

Reputation: 3616

Get the values of an array from indices in another array: Matlab

I have a 20x1 double array A, and a 1000x1 double array B.

I want to get array C, where array C will be 1000x1 double where the values in B are used to index the values in A like so:

C(1) = A(B(1))
C(2) = A(B(2))
...
C(i) = A(B(i))
...
c(1000) = A(B(1000))

How this can be done?

Upvotes: 0

Views: 1679

Answers (2)

Wolfie
Wolfie

Reputation: 30165

You don't need a loop for this, you can directly use:

C = A(B)

This takes advantage of MATLAB's matrix indexing, which is the way indexing is handled in MATLAB when an array is used instead of an integer.

Take a look at the docs: https://uk.mathworks.com/help/matlab/math/matrix-indexing.html

For example:

A = [11 12 13];
B = [1 2 3 1 2 3 3 2 1];
C = A(B)

C =

11    12    13    11    12    13    13    12    11

Ensure that B only contains integers which are valid indices of A (not less than 1 or greater than the length of A).

Upvotes: 4

Tak
Tak

Reputation: 3616

I did it using for loop as shown below, not sure if this is the ideal solution:

C = zeros(1000,1);

for i = 1:1000
    C(i,1) = A(B(i));
end 

Upvotes: 0

Related Questions