# 高效地产生反对称矩阵

``````function test1(d::Int64, D::Int64, v::Vector{Float64})
L = d * D
A = zeros(eltype(v),(L, L))
count = 1
for j = 1:L
for i=1:L
if i > j
A[i,j] = v[count]
A[j,i] = -v[count]
count += 1
end
end
end
return A
end
``````

``````const A = zeros(Float64, (100, 100)) # L = 100
function test1(v::AbstractVector, L::Int)
# A = zeros(Float64, (L, L))
count = 1
@inbounds for i = 1:L, j = 1:L
if i > j
A[i, j] = v[count]
A[j, i] = -v[count]
count += 1
end
end
return A
end

using BenchmarkTools
v = rand(4950)
@btime test1(\$v, 100);
``````

1 个赞

``````function test2(d::Int64, D::Int64, v::Vector{Float64})
L = d * D
A = zeros(eltype(v),(L, L))

for i = 2:L
for j = 1:i-1
A[i,j] = -v[(i-2)*(i-1)/2+j]
end
end
return A-transpose(A)
end

``````

100维的反对称矩阵，大概快5us(15.658-> 10.524)

2 个赞

``````A = Array{eltype(v)}(undef, L, L)
@inbounds for i in 1:L, j in 1:L
A[j, i] = if i > j
v[((i-1)*(i-2))>>1+j]
elseif i < j
-v[((j-1)*(j-2))>>1+i]
else
0
end
end

``````

@LDA111222 抱歉没表述好，我是想说用索引来并行的点子不错，然后补充了可能的改进。。。

1 个赞