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

后端 未结 2 1119
旧巷少年郎
旧巷少年郎 2020-12-07 01:27
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

相关标签:
2条回答
  • 2020-12-07 02:04

    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.

    0 讨论(0)
  • 2020-12-07 02:08
    v = a(sub2ind(size(a), b, 1:length(b)))
    

    sub2ind transforms subscripts into a single index.

    0 讨论(0)
提交回复
热议问题