apply bsxfun and arrayfun to every row of a matrix

16 views (last 30 days)
There is two matrix, 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?

Answers (1)

Matt J
Matt J on 10 Nov 2013
Edited: Matt J on 11 Nov 2013
In your example, there is no need to use bsxfun or arrayfun. rectint(A,B) will produce exactly the matrix you are looking for.
  5 Comments
zhang
zhang on 11 Nov 2013
@Matt J, Thanks so much for the help. Let's assume f can support what you asked. One more question, if A is a 1x4 and B is mx4, is there any way to apply function f(just support f(1x4, 1x4))to each row of A and B without using loop
Matt J
Matt J on 11 Nov 2013
If your f() supports what I asked about, then bsxfun can be used
I=1:size(A,1);
J=1:size(B,1);
F=@(i,j) f(A(i,:), B(j,:));
bsxfun(F,I.',J);
if A is a 1x4 and B is mx4, is there any way to apply function f(just support f(1x4, 1x4))to each row of A and B without using loop
Not really. You can hide the loop inside arrayfun, but it won't be faster
arrayfun(@(j) f(A,B(j,:)) , J.');

Sign in to comment.

Categories

Find more on Structures in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!