Azzera filtri
Azzera filtri

Operation without for loop

1 visualizzazione (ultimi 30 giorni)
Sukuchha
Sukuchha il 31 Gen 2012
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 ?

Risposta accettata

Andrei Bobrov
Andrei Bobrov il 31 Gen 2012
Y = arrayfun(@(i1)myfunction(A(i1,:), B(i1,:)), 1:size(A,1))
  3 Commenti
Sean de Wolski
Sean de Wolski il 31 Gen 2012
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 il 31 Gen 2012
Thanks all for the input, i used andrei method. It seems to be working but havent check its performance of against for loop.

Accedi per commentare.

Più risposte (1)

Walter Roberson
Walter Roberson il 31 Gen 2012
You can make it look prettier using arrayfun(), but arrayfun() is just going to be doing the "for" loop internally.
  4 Commenti
Sukuchha
Sukuchha il 31 Gen 2012
yeh, i wanted something which would be faster than for loop, otherwise i would have done with for loop :)
Walter Roberson
Walter Roberson il 31 Gen 2012
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.

Accedi per commentare.

Categorie

Scopri di più su Creating and Concatenating Matrices in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by