apply bsxfun and arrayfun to every row of a matrix
Mostra commenti meno recenti
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 Commenti
Does f() support inputs like
f(A(i,:), B)
and
f(A,B(j,:))
Azzi Abdelmalek
il 10 Nov 2013
Can you give an example?
zhang
il 10 Nov 2013
Risposte (1)
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 Commenti
zhang
il 11 Nov 2013
Matt J
il 11 Nov 2013
It depends on the answers to the questions I asked you above.
Azzi Abdelmalek
il 11 Nov 2013
zhang, result = rectint(A, B) and your code give the same size but not the same values
zhang
il 11 Nov 2013
Matt J
il 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.');
Categorie
Scopri di più su Matrix Indexing in Centro assistenza e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!