Operation without for loop
2 次查看(过去 30 天)
显示 更早的评论
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 ?
0 个评论
采纳的回答
Andrei Bobrov
2012-1-31
Y = arrayfun(@(i1)myfunction(A(i1,:), B(i1,:)), 1:size(A,1))
3 个评论
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( :-).
更多回答(1 个)
Walter Roberson
2012-1-31
You can make it look prettier using arrayfun(), but arrayfun() is just going to be doing the "for" loop internally.
4 个评论
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.
另请参阅
类别
在 Help Center 和 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!