Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Singleton vector different from its transpose in Julia

If I define A = [1] I get that A is not equal to A' since they are of different types:

julia> A=[1]
1-element Array{Int64,1}:
 1

julia> A'
1×1 LinearAlgebra.Adjoint{Int64,Array{Int64,1}}:
 1

julia> A == A'
false

If I define another vector B = [1, 2, 3] and I try to do the products with A'and A I obtain the following output:

B=[1,2,3]
3-element Array{Int64,1}:
 1
 2
 3

julia> B*A'
3×1 Array{Int64,2}:
 1
 2
 3

julia> B*A
ERROR: MethodError: no method matching *(::Array{Int64,1}, ::Array{Int64,1})
...
...

That seems a problem of * operator signature that seems not to accept two Array{Int64,1} as operands while defining another vector C = [4 5] we get:

julia> C=[4 5]
1×2 Array{Int64,2}:
 4  5

julia> B*C
3×2 Array{Int64,2}:
  4   5
  8  10
 12  15

So * is defined for operands of types Array{Int64,1} and Array{Int64,2} respectively. Why I cannot multiply a column vector by a singleton vector A but I can using A'?

like image 860
PrinceOfBorgo Avatar asked Apr 23 '26 09:04

PrinceOfBorgo


2 Answers

The answer to this depends on how well you understand linear algebra. Julia follows the conventions of linear algebra for it's array multiplication, if you need to brush up, wikipedia's page is a good source.

It boils down to the fact that your A is a column vector whereas A' is a row vector (like C). Matrix multiplication is defined between (n, k) and (k, m) matrices to produce a (n, m) matrix. Column vectors can sometimes be thought of as (n, 1) matrices, so there's no well defined notion of multiplication between two column vectors.

If you want the dot product, use the dot function (you'll need to do using LinearAlgebra first). If you want an element-wise product, you can use the broadcasting notation, u .* v.

like image 88
Mason Avatar answered Apr 25 '26 23:04

Mason


In Julia Vectors are one dimensional Arrays, while the transposition works on two dimensional matrices (Array{T,2} equivalent to Matrix{T})

julia> A=[1]
1-element Array{Int64,1}:
 1

julia> collect(A')
1×1 Array{Int64,2}:
 1

Since transposition in Julia does not materialize the data and rather holds reference to the original I needed to use collect to actually see what is going on.

When using multiplication on 2-dimensional arrays you are actually using linear algebra operations.

If you want to multiply element-wise use the dot . operator instead:

julia> A .== A'
1×1 BitArray{2}:
 1

Note it return an Array rather than a single value.

If you want to multiply element-wise (rather than using linear algebra matrix multiplication) you need to vectorize again:

julia> B.*A
3-element Array{Int64,1}:
 1
 2
 3
like image 23
Przemyslaw Szufel Avatar answered Apr 25 '26 23:04

Przemyslaw Szufel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!