dalibocai
dalibocai

Reputation: 2347

How to select one element from each column of a matrix in matlab?

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]?

Upvotes: 8

Views: 2793

Answers (2)

Pursuit
Pursuit

Reputation: 12345

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.

Upvotes: 0

cyborg
cyborg

Reputation: 10139

v = a(sub2ind(size(a), b, 1:length(b)))

sub2ind transforms subscripts into a single index.

Upvotes: 5

Related Questions