Apply function to every pair of columns in two matrices in MATLAB

后端 未结 2 1657
走了就别回头了
走了就别回头了 2021-01-06 20:30

In MATLAB, I\'d like to apply a function to every pair of column vectors in matrices A and B. I know there must be an efficient (non for

相关标签:
2条回答
  • 2021-01-06 20:44

    Do you mean pairwise? So in a for-loop the function will work as scalar_val = func(A(i),B(i))?

    If A and B have the same size you can apply ARRAYFUN function:

    newvector = arrayfun(@(x) func(A(x),B(x)), 1:numel(A));
    

    UPDATE:

    According your comment you need to run all combinations of A and B as scalar_val = func(A(i), B(j)). This is a little more complicated and for large vectors can fill the memory quickly.

    If your function is one of standard you can try using BSXFUN:

    out = bsxfun(@plus, A, B');
    

    Another way is to use MESHGRID and ARRAYFUN:

    [Am, Bm] = meshgrid(A,B);
    out = arrayfun(@(x) func(Am(x),Bm(x)), 1:numel(Am));
    out = reshape(out, numel(A), numel(B));
    

    I believe it should work, but I don't have time to test it now.

    0 讨论(0)
  • 2021-01-06 20:57

    Try

    na = size(A,1);
    nb = size(B,1);
    newvector = bsxfun(@(j,k)(func(A(j,:),B(k,:))),1:na,(1:nb)');
    

    bsxfun performs singleton expansion on 1:na and (1:nb)'. The end result, in this case, is that func will be applied to every pair of column vectors drawn from A and B.

    Note that bsxfun can be tricky: it can require that the applied function support singleton expansion itself. In this case it will work to do the job you want.

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