Undesired behaviour of bsxfun and colon-operator
2 views (last 30 days)
Show older comments
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?
1 Comment
Stephen23
on 22 May 2019
Edited: Stephen23
on 23 May 2019
"Undesired behaviour of bsxfun and colon-operator"
You might consider this to be undesired behavior, but the cause is that your function is not truly vectorized, as required by the bsxfun documentation:
"fun must support scalar expansion, such that if A or B is a scalar, then C is the result of applying the scalar to every element in the other input array.
A simple example shows that this is not the case when x is scalar and y is non-scalar:
>> F = @(x,y)x+sum(0:y);
>> F([1;2;3],5) % Vectorized.
ans =
16
17
18
>> F(6,[7,8,9]) % Not vectorized!
ans = 34
This is due to how the colon operator interprets non-scalar arguments, and bsxfun changing the orientations of the arguments that it provides to your function.
Accepted Answer
Stephen23
on 22 May 2019
Edited: Stephen23
on 22 May 2019
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
0 Comments
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!