Undesired behaviour of bsxfun and colon-operator

1 回表示 (過去 30 日間)
Michael Klanner
Michael Klanner 2019 年 5 月 22 日
編集済み: Stephen23 2019 年 5 月 23 日
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
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
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

その他の回答 (2 件)

Matt J
Matt J 2019 年 5 月 22 日
bsxfun(@(x,y)x+y.*(y+1)/2,1,6:9)
  1 件のコメント
Matt J
Matt J 2019 年 5 月 22 日
編集済み: Matt J 2019 年 5 月 22 日
Better:
f=@(z) z.*(z+1)./2;
bsxfun(@plus,(1:3).', f(6:9))

サインインしてコメントする。


Matt J
Matt J 2019 年 5 月 22 日
bsxfun(@(x,y)x+arrayfun(@(z)sum(0:z),y),1,6:9)

カテゴリ

Help Center および File ExchangeOperators and Elementary Operations についてさらに検索

製品

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by