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 m
xn
. 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?
B = rowfun( func , A , Name,Value ) applies the function func to each row of the table A with additional options specified by one or more Name,Value pair arguments. For example, you can specify which variables to pass to the function func and how to call func .
B = arrayfun( func , A ) applies the function func to the elements of A , one element at a time. arrayfun then concatenates the outputs from func into the output array B , so that for the i th element of A , B(i) = func(A(i)) .
The all function reduces such a vector of logical values to a single condition. In this case, B = all(A < 0.5) yields logical 0 . This makes all particularly useful in if statements. The code is executed depending on a single condition, rather than a vector of possibly conflicting conditions.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With