Undesired behaviour of bsxfun and colon-operator
1 回表示 (過去 30 日間)
古いコメントを表示
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 件のコメント
Stephen23
2019 年 5 月 22 日
編集済み: Stephen23
2019 年 5 月 23 日
"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.
採用された回答
Stephen23
2019 年 5 月 22 日
編集済み: Stephen23
2019 年 5 月 22 日
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 件のコメント
参考
カテゴリ
Help Center および File Exchange で Operators and Elementary Operations についてさらに検索
製品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!