apply bsxfun and arrayfun to every row of a matrix

4 Ansichten (letzte 30 Tage)
zhang
zhang am 10 Nov. 2013
Kommentiert: Matt J am 11 Nov. 2013
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 Kommentare
Azzi Abdelmalek
Azzi Abdelmalek am 10 Nov. 2013
Can you give an example?
zhang
zhang am 10 Nov. 2013
I've gave an example now. Please have a look at it.

Melden Sie sich an, um zu kommentieren.

Antworten (1)

Matt J
Matt J am 10 Nov. 2013
Bearbeitet: Matt J am 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 Kommentare
zhang
zhang am 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 am 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.');

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Matrix Indexing finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by