问题
There are two matrices, A and B with size m-by-4 and n-by-4 respectively. My question is how to apply a function f, which takes two 1x4 vectors as input, on every row of A and B. The result will be a matrix with size mxn. The element [i, j] in result is f(A(i, :), B(j, :)).
For example:
A = rand(3, 4);
B = rand(5, 4);
for i = 1 : 3
for j = 1 : 5
result(i, j) = rectint(A(i, :), B(j, :));
end
end
Can I use bsxfun or arrayfun to do this job?
回答1:
You can use arrayfun, if you first use meshgrid to generate all combinations of rows:
[ii jj] = meshgrid(1:size(A,1),1:size(B,1));
result = arrayfun(@(n) rectint( A(ii(n),:), B(jj(n),:) ), 1:numel(ii) );
result = reshape(result, size(B,1), size(A,1)).';
You could of course substitute rectint by any other function that accepts two vector inputs and returns a number.
回答2:
This functionality is built into rectint. For the syntax rectint(A,B):
AandBcan also be matrices, where each row is a position vector.AREAis then a matrix giving the intersection of all rectangles specified byAwith all the rectangles specified byB. That is, ifAisM-by-4andBisN-by-4, thenAREAis anM-by-Nmatrix...
So, you can just do result = rectint(A,B); to get the matrix you are after.
来源:https://stackoverflow.com/questions/19896630/apply-bsxfun-or-arrayfun-to-every-row-of-a-matrix