how bsxfun works? the result is weird.
Show older comments
why the result of this statement
z1=bsxfun(@(y1,y2)(y1+[y2(2:end),24]),zeros(4,1),1:4)
is
z1 =
24 24 24 24
24 24 24 24
24 24 24 24
24 24 24 24
4 Comments
z1=bsxfun(@plus, zeros(4,1),[2:4 24])
is what I would do to achieve what I assume you are trying to do. To be honest I have never used bsxfun similar to how you are doing, but its result does surprise me a little. It is one of those functions I understand for the usages I have done myself, but not in its full wider usage.
John D'Errico
on 17 Dec 2015
Edited: John D'Errico
on 17 Dec 2015
I fixed your question to read properly, as the matrix result appeared to show up as a vector.
James
on 17 Dec 2015
John D'Errico
on 17 Dec 2015
You cannot index into the variable that is passed into bsxfun, expecting to use it as a vector.
The idea behind bsxfun (as you are using it) is that it takes a pair of vectors, then acts on every combination of elements. The function is applied to pairs of scalars here, as essentially an outer product. bsxfun does NOT apply the function to vectors! It applies the function to all combinations of scalar elements.
So you get bsxfun "confused" when you try this. Yes, it is non-obvious, but this is how bsxfun acts.
Accepted Answer
More Answers (1)
John D'Errico
on 17 Dec 2015
This appears to be a bug in BSXFUN, since the result of the operation
[y2(2:end),24]
is to create the vector [2 3 4 24]. So lets try a variation of your problem. First, as you posed it.
y1 = zeros(4,1);
y2 = 1:4;
z1=bsxfun(@(y1,y2)(y1+[y2(2:end),24]),y1,y2)
z1 =
24 24 24 24
24 24 24 24
24 24 24 24
24 24 24 24
And we see the array of all 24 elements as you found. Now, let me change it in a way that should not be relevant.
y2 = 1:4
y2 =
1 2 3 4
y2 = [y2(2:end),24]
y2 =
2 3 4 24
z1=bsxfun(@(y1,y2)(y1+y2),y1,y2)
z1 =
2 3 4 24
2 3 4 24
2 3 4 24
2 3 4 24
As you see, BSXFUN now gives the proper answer.
My guess is the parser is screwing something up here, that the answer is not in BSXFUN directly, since BSXFUN works properly when it is fed those vectors in simpler form.
4 Comments
Sean de Wolski
on 17 Dec 2015
Edited: Sean de Wolski
on 17 Dec 2015
I think it's just a limitation in that you're not supposed to index inside of fun() since that's not singleton. This should be rewritten as:
z1=bsxfun(@(y1,y2)(y1+y2),y1,[y2(2:end),24])
John D'Errico
on 17 Dec 2015
Yes, I accept that since y2 is an argument to bsxfun, that indexing into y2 will cause a problem. So clearly not a bug. Indexing into y2, INSIDE of the function handle that bsxfun gets will cause a problem.
Guillaume
on 17 Dec 2015
No, there's no bug in bsxfun. y2 is scalar, so y2(2:end) is empty.
John D'Errico
on 17 Dec 2015
I said exactly that in my comment, recognizing there is no bug.
Categories
Find more on Matrix Indexing 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!