Search code examples
matlabfor-loopbinary-operators

Advanced subscript assignment to avoid a for loop in MATLAB--many binary operations at once


I've got a big array, say A, with values in {1,...,n}, and another array B of the same size.

I want to get all of the following:

B(A==1)
B(A==2)
...
B(A==n)

and then do something else with the results (not so important for now).

I tried things like:

[x,y] = B(A==[1:n])

and

[x,y] = [B(A==1), B(A==2), ..., B(A==n)]

Of course to no avail.

The for loop approach

for ii=1:n
    dummy=B(A==1)
    other stuff
end

works, but I'm convinced I can avoid for loops for everything in MATLAB! Stuck here, though. Any suggestions? Perhaps some sort of inline anonymous function call?


Solution

  • arrayfun is your friend for things like this, hopefully you can see how to modify this for your own use:

    A=randi(5,10,10)
    B=rand(10)
    C=arrayfun(@(i) B(A==i),1:5,'UniformOutput',false)
    C{1} % for example, gives B(A==1)
    

    C is a cell array.

    Beware that the for loop may be faster for larger problems. It would be a good idea to do some tests to see whether arrayfun is actually faster. Look at this question and its answers to learn a bit more about this. There may be some way to do this without using arrayfun, but I can't think of it!