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

In MATLAB, I would like to apply a function to each pair of column vectors in matrices `A`

and `B`

. I know there must be an efficient (not `for`

) way to do this, but I cannot figure it out. The function will output a scalar.

+3

source to share

Try

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

```

`bsxfun`

performs one-color expansion by 1: na and (1: nb) '. The end result in this case is that func will be applied to every pair of column vectors taken from A and B.

Note that bsxfun can be tricky: it may require the application function to support singleton expansion. In this case, it will work to get the job done.

+7

source

Do you mean in pairs? So during the loop, the function will work like `scalar_val = func(A(i),B(i))`

?

If `A`

both `B`

are the same size, you can use the ARRAYFUN function :

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

```

UPDATE

As per your comment, you need to execute all combinations of A and B as `scalar_val = func(A(i), B(j))`

. This is a little more complicated and for large vectors it can fill up memory quickly.

If your function is 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.

+1

source

All Articles