apply bsxfun and arrayfun to every row of a matrix

4 visualizaciones (últimos 30 días)
zhang
zhang el 10 de Nov. de 2013
Comentada: Matt J el 11 de Nov. de 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 comentarios
Azzi Abdelmalek
Azzi Abdelmalek el 10 de Nov. de 2013
Can you give an example?
zhang
zhang el 10 de Nov. de 2013
I've gave an example now. Please have a look at it.

Iniciar sesión para comentar.

Respuestas (1)

Matt J
Matt J el 10 de Nov. de 2013
Editada: Matt J el 11 de Nov. de 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 comentarios
zhang
zhang el 11 de Nov. de 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 el 11 de Nov. de 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.');

Iniciar sesión para comentar.

Categorías

Más información sobre Matrix Indexing en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by