tags:

views:

46

answers:

2

Assuming a vector (or matrix) of ids

>  1 2 3 3 2

Let's suppose each of these ids corresponds to a numerical value, stored in another vector

14 33 25

I'd like to replace the ids by their corresponding value to build the following vector

14 33 25 25 33

There must be a simple way to achieve this without resorting to loops, but my brain fails me at the moment, and I couldn't find anything in the documentation. Any ideas?

+8  A: 

assuming:

x = [14 33 25]

ind = [1 2 3 3 2]

then

x(ind) = 14 33 25 25 33
Nathan Fellman
Thanks! I knew it had to be trivial. Do you know where in the documentation I should have found this? Or how Matlab calls that method?
Kena
@Kena: this falls under the general topic of Matlab array indexing and munging. See "help paren" for its reference documentation, and "help punct" for related operators. It's covered in the online documentation in MATLAB > Getting Started > Matrices and Arrays. The "doc ismember" and "doc find" pages cover some related indexing usage that could help shed light on this.
Andrew Janke
A: 

For what it's worth, it works also with python+numpy:

x = array([14,33,25])
ind = [0,1,2,2,1]
x[ind] # -> array([14, 33, 25, 25, 33])
Olivier
This is incorrect, because indexing in Matlab starts at 1, not at 0.
Nathan Fellman
@Nathan: it is correct, because it is in **Python**.
Olivier
@Olivier, you're right, I missed that.
Nathan Fellman

related questions