Operation without for loop

I have two matrix.MAtrix A(250000x4)and MAtrix B(250000x4)
I have a function which result a scalar C.
C = myfunction(X,Y);
Now i want to pass each row of MAtrixA and MAtrixB to myfunction without using a for loop.
How to do it ?

 채택된 답변

Andrei Bobrov
Andrei Bobrov 2012년 1월 31일

0 개 추천

Y = arrayfun(@(i1)myfunction(A(i1,:), B(i1,:)), 1:size(A,1))

댓글 수: 3

Walter Roberson
Walter Roberson 2012년 1월 31일
That's what I was thinking.
Now... can it be done with bsxfun() ? ;-)
Sean de Wolski
Sean de Wolski 2012년 1월 31일
Sure. Permute B so that it is [1x4x250000].
bsxfun(@myFunction,A,permute(B,[3 2 1]));
It's going to use a ton of memory and probably be slower though. Of course, it's still awesomer because it uses bsxfun( :-).
Sukuchha
Sukuchha 2012년 1월 31일
Thanks all for the input, i used andrei method. It seems to be working but havent check its performance of against for loop.

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

추가 답변 (1개)

Walter Roberson
Walter Roberson 2012년 1월 31일

0 개 추천

You can make it look prettier using arrayfun(), but arrayfun() is just going to be doing the "for" loop internally.

댓글 수: 4

Sukuchha
Sukuchha 2012년 1월 31일
is arrayfun() is faster than for loop ? I tried with arrayfun but arrayfun in passing one element of matrix A and one element of matrix B, not the whole row of matrix A and matrix B .
fh = @(x,y)(myfunction(x, y));
[Y]=arrayfun(fh, A,B,'UniformOutput',false)
Walter Roberson
Walter Roberson 2012년 1월 31일
I would not expect arrayfun() to be faster than a "for" loop. Your initial question was, however, not about performance; it was about applying the operation without using a "for" loop.
Sukuchha
Sukuchha 2012년 1월 31일
yeh, i wanted something which would be faster than for loop, otherwise i would have done with for loop :)
Walter Roberson
Walter Roberson 2012년 1월 31일
Often in such cases the best thing to do is rewrite the function so that it accepts arrays.
Note that "for" loops are not necessarily slow, especially in new versions. There is probably more overhead in calling myfunction all those times than there is in the "for" loop itself.

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

카테고리

도움말 센터File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by