Create matrix, such that each row is the difference of an array with one of its values

Hey ! I was wondering if there was an efficient if given an array

a = [x_1,...,x_i]

to get a matrix that is given by

M = [[x_1-x_1,x_2-x_1,...,x_i - x_1],[x_1-x_2,x_2-x_2,...,x_i - x_2] ,etc.]

The only thing I have in my mind is

t_array = [x1,x2,x3,etc]
a = Array{Array}(undef, 1, length(t_array))
for i in 1:length(t_array)
a[i] = t_array[:] .- t_array[i]
end
Is there a package of any use that could be used ??

Do you want a matrix or a vector of vectors? They’re not the same thing in Julia.

I’d just do a' .- a to create the matrix. Or for the vector of vectors use a comprehension:

julia> using Symbolics

julia> @variables x₁ x₂ x₃ x₄;

julia> a = [x₁, x₂, x₃, x₄]
4-element Vector{Num}:
 x₁
 x₂
 x₃
 x₄

julia> a' .- a
4×4 Matrix{Num}:
       0  x₂ - x₁  x₃ - x₁  x₄ - x₁
 x₁ - x₂        0  x₃ - x₂  x₄ - x₂
 x₁ - x₃  x₂ - x₃        0  x₄ - x₃
 x₁ - x₄  x₂ - x₄  x₃ - x₄        0

julia> [a .- x for x in a]
4-element Vector{Vector{Num}}:
 [0, x₂ - x₁, x₃ - x₁, x₄ - x₁]
 [x₁ - x₂, 0, x₃ - x₂, x₄ - x₂]
 [x₁ - x₃, x₂ - x₃, 0, x₄ - x₃]
 [x₁ - x₄, x₂ - x₄, x₃ - x₄, 0]
6 Likes

Great shortcut thanks !

I ran a quick test with the following expressions.
I would have expected a different result for the last one.
Can someone explain to me what and how is checked (or even transformed!?) to have
A+A'==zeros(4,4) true?

julia> A=a' .- a
4×4 Matrix{Num}:
       0  x₂ - x₁  x₃ - x₁  x₄ - x₁
 x₁ - x₂        0  x₃ - x₂  x₄ - x₂
 x₁ - x₃  x₂ - x₃        0  x₄ - x₃
 x₁ - x₄  x₂ - x₄  x₃ - x₄        0

julia> A+A'==zeros(eltype(A),size(A))
true

julia> A+A'==zeros(4,4)
true