Friday 22 August 2014

Binary function with singleton expansion

BSXFUN( function,  A, B )

This great function really helps when you want to do an "outer product". That is, if you need to combine each item in list A with each item in list B. It generalises to any number of dimensions, too!

  • "Binary function with singleton expansion" is a fancy way of saying automatic dimension replication.
  •  A binary function is simply any function that takes two parameters. For example "plus(A,B)", which is the function that does A+B
  • Often repmat can be replaced  with BSXFUN. I'm not sure whether this improves readability or not, but it works well in some situations.
    BSXFUN(@plus, [1,2,3],[5;6])
        = [ 6 7  8
            7 8 9 ]

    BSXFUN(@gt, [1 2 3 4 5 6 7 8 9],[3; 6]) =
              = [0 0 0 1 1 1 1 1 1
                 0 0 0 0 0 0 1 1 1 ]

    note the following useful binary operations:
  • gt(a,b) = a>b (greater than)
  • lt(a,b) = a<b ( less than)
  • ge, le (greater-or-equal, less-or-equal)
  • plus, times, rdivide
* note that you can usually achieve the same thing with repmat, The disadvantage of REPMAT is that you have to know the sizes explicitly, or calculate them explicitly
    Y = BSXFUN(@plus, [1 2 3],[5;6])
   is the same as
    Y = plus(repmat([1 2 3], 2,1), repmat([5;6],1,3)    or
    Y = repmat([1 2 3],2,1)+repmat([1;2],1,3)  or
* as another example, if you wanted to create the times-tables for 1 to 12:
    BSXFUN(@times,[1:12]',[1:12])
* Note that singleton expansion is automatic for scalars! i.e.
    1+V  == ones(size(V)) + V
    2*V   == times(2*ones(size(V)), V)

   Python's numpy automatically expands dimensions for standard binary operations.

 Also try combining these techniques with
    - creating quick functions
    - matrix multiplication expansion

No comments:

Post a Comment