MATLAB: Undesired behaviour of bsxfun and colon-operator

bsxfuncolon operatorMATLABsum

I have a problem using bsxfun for a certain user-defined function. A simplified version of it looks like this:
bsxfun(@(x,y)x+sum(0:y),(1:3)',6:9)
ans =
22 29 37 46
23 30 38 47
24 31 39 48
This does exactly what I want. But if i use it with a single number of x it gives me:
bsxfun(@(x,y)x+sum(0:y),1,6:9)
ans =
22
While I would like to get
ans =
22 29 37 46
Any ideas to build a workaround for this problem?

Best Answer

  • A robust workaround using ndgrid and arrayfun and exactly the same function:
    >> [X,Y] = ndgrid(1:3,6:9);
    >> arrayfun(@(x,y)x+sum(0:y),X,Y)
    ans =
    22 29 37 46
    23 30 38 47
    24 31 39 48
    >> [X,Y] = ndgrid(1,6:9);
    >> arrayfun(@(x,y)x+sum(0:y),X,Y)
    ans =
    22 29 37 46