Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MATLAB: Mapping Values to Index of Other Array

Can any MATLAB experts help out with this:

I have the following two arrays:

A = [1 1 3 4 4 4 4 4];
B = [6 7 8 9];

I would like to make a third array that uses the values of "A" as sort of pointers to the array in B. So, the final result would be:

C = [6 6 8 9 9 9 9 9];

Every element of "A" is mapped to an index in "B".

Thanks in advance.

Edit: Sorry, forgot to mention: I'm looking for a non-loop solution. This would work (I think), but it uses looping:

C = [];
for i = 1:length(A)
   C = [C B(A(i))];
end
like image 901
Eric Avatar asked Apr 17 '11 03:04

Eric


People also ask

How do you find the common values between two arrays in Matlab?

C = intersect( A,B ) returns the data common to both A and B , with no repetitions. C is in sorted order. If A and B are tables or timetables, then intersect returns the set of rows common to both tables.

Can you index an array in Matlab?

In general, you can use indexing to access elements of any array in MATLAB regardless of its data type or dimensions.

How do you find the index of an element in an array in Matlab?

k = find( X ) returns a vector containing the linear indices of each nonzero element in array X . If X is a vector, then find returns a vector with the same orientation as X . If X is a multidimensional array, then find returns a column vector of the linear indices of the result.


1 Answers

Use B(A). It treats the elements of A as indices into B and returns the an array with the same size as A.

like image 177
Pablo Avatar answered Nov 14 '22 21:11

Pablo