One-dimensional matrix and vectors in broadcast

In a recent thread I noticed that mutating a vector by broadcasting operations on one-dimensional matrices does not work:

julia> x = rand(3,1);

julia> z = zeros(3);

julia> z .= x 
ERROR: DimensionMismatch("cannot broadcast array to have fewer dimensions")

On the other side, the symmetric mutation does work:

julia> x .= z
3×1 Array{Float64,2}:
 0.0
 0.0
 0.0

Looks like something that could be improved from a user perspective. Is there any design reason for this, an implementation difficulty, or what?

I found some discussions related to this, but perhaps there is a more clear view on the subject now.

3 Likes

What do you have in mind?

Julia’s broadcasting mechanism generally rejects incompatible dimensions (in contrast to, say, R’s “recycling”). See, in particular, ?broadcast, which tells you that

Singleton and missing dimensions are expanded to match the extents of the other arguments by virtually repeating the value.

This is what’s happening in x .= z above.

1 Like

Yes, I think it would not be unreasonable to allow this. Feel free to open an issue on GitHub.

3 Likes

From a user perspective just that it worked. I tried to follow the function call, but the way broadcasting is implemented is way too complicated for me.

Done: broadcast (Nx1)-dimensional array to vector does not work · Issue #39904 · JuliaLang/julia · GitHub

4 Likes

I don’t disagree with your issue, but to nitpick: Julia would normally call x a two-dimensional array 3×1 Array{Float64,2}, where one of the dimensions is 1, to be distinguished from one-dimensional Vector. Of course, Matlab treats them as the same, but Julia doesn’t. Not sure what they should be called here, maybe 1-column matrix?

Well, that was quick: allow trailing dims in inplace broadcast by simeonschaub · Pull Request #39859 · JuliaLang/julia · GitHub, thank you @simeonschaub

4 Likes

Gotta love it when the patch precedes the issue :stuck_out_tongue:

4 Likes