a = [1 1 1; 2 2 2; 3 3 3];
b = [1 2 3];
How can I call one function to get a vector v[i] = a[b[i],i
Another thing to try, keeping very close to your description, you can use the arrayfun
function.
First define a function that maps a value x
to the desired output.
fn = @(x) a(b(x), x);
Then call that function on each input in the the i
vector.
i = 1:3;
v = arrayfun(fn, i);
Or, this can all be done in a single line, in the obvious way:
v = arrayfun(@(x) a(b(x), x), 1:3);
This arrayfun
is simply shorthand for the loop below:
for ixLoop = 1:3
v(ixLoop) = a(b(ixLoop),ixLoop);
end
The related functions arrayfun
, cellfun
, and structfun
have similar uses, and are strangely empowering. This Joel article convinced me to be a believer.
v = a(sub2ind(size(a), b, 1:length(b)))
sub2ind
transforms subscripts into a single index.