Lepidopterist
Lepidopterist

Reputation: 411

Treating a vector as a function on its indices/applying this function to another vector (of indices)

Let y=[4;6;2;9;5;1] be a column vector and let i=[4,2,1] be a vector of indices. I would like to somehow "apply" i to y and obtain [9,6,4]. Or at least [4;2;0;9;0;0].

There is clearly a way to do this with a for loop. I was advised by someone on this site never to use a for loop in MATLAB. Is there some logical operator I can use here? Ideally one could treat y as a function on its indices and apply y to i as a function. Is this possible, or should I go with the old reliable for loop?

Upvotes: 0

Views: 34

Answers (1)

Jonas
Jonas

Reputation: 74930

Simple:

y(i)

returns your result [9 6 4].

To set all the elements that are not part of the index-list to zero, you can copy the specified elements:

out = zeros(size(y));
out(i) = y(i);

Upvotes: 1

Related Questions