# View a scalar as a vector/array

Is there is any built-in mechanism in Julia to “view” a scalar quantity, like a number, as an array? I am thinking something like as follows, given that the shape of `b` and `c` could be broadcast against `A`.

``````A = ones(3, 3)
b = 1
c = ones(3)

A .+ b == A .+ c  # works, since b and c can each be broadcast to the shape of A
A + B == a .+ B  # true
A + C == a .+ C  # true
``````

I think `numpy` has a function `broadcast_to` like I am illustrating here. This could be useful if, e.g., you were solving a matrix equation with a constant vector on the right-hand side.

``````A = ones(3, 3)
x = A \ b
x == A .\ ones(3)
``````

Note that, consistent with other broadcast functions, doing `A .\ b` broadcasts `b=1` to a 3x3 matrix of `1`s, so `A .\ b == A \ ones(3,3)`.

3 Likes

What? Unless I misunderstand, this is wrong:

``````jl> A = rand(3,3);

jl> A .\ ones(3, 3)
3×3 Matrix{Float64}:
4.47187  475.907    4.43528
1.494      2.97416  6.40232
2.93817    1.11483  3.30267

jl> A \ ones(3, 3)
3×3 Matrix{Float64}:
0.872241   0.872241   0.872241
-0.422581  -0.422581  -0.422581
3.57412    3.57412    3.57412
``````

It doesn’t just broadcast the shapes, but also does elementwise operations.

Yes you are right and thanks for pointing that out – beginner mistake for me thinking about broadcasting backwards.

``````julia> A = rand(3, 3)
3×3 Matrix{Float64}:
0.96678   0.876051  0.849013
0.966259  0.257086  0.658442
0.818418  0.825752  0.210322

julia> A .\ ones(3,3) == A .\ ones(3) == A .\ 1  # All elementwise inverse of each element of A
true

A \ ones(3,3) == A .\ 1
false
``````