apply bsxfun and arrayfun to every row of a matrix

조회 수: 9 (최근 30일)
zhang
zhang 2013년 11월 10일
댓글: Matt J 2013년 11월 11일
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?
  댓글 수: 3
Azzi Abdelmalek
Azzi Abdelmalek 2013년 11월 10일
Can you give an example?
zhang
zhang 2013년 11월 10일
I've gave an example now. Please have a look at it.

댓글을 달려면 로그인하십시오.

답변 (1개)

Matt J
Matt J 2013년 11월 10일
편집: Matt J 2013년 11월 11일
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
zhang
zhang 2013년 11월 11일
@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 2013년 11월 11일
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.');

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Structures에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by