使用数组进行数组内索引 [英] Using an array for in array indexing

查看:73
本文介绍了使用数组进行数组内索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有更好的方法吗?

a = rand(10,10)
a[[CartesianIndex(i,i) for i in 1:10]] .= something

即使用setindex!没有CartesianIndex或类似

I.e. using setindex! without a CartesianIndex or something like

a[i,i for i in 1:10] .= something

还是通常将setindex!与用于语法的数组一起使用?

Or in general using setindex! with an array for syntax?

推荐答案

我只是想总结一下所有答案和注释,以查看每个建议解决方案的性能.

I just wanted to sum up all the answers and comments looking at the performance of each proposed solution.

using LinearAlgebra, BenchmarkTools
A = rand(1000, 1000)
B  = [i == j for i ∈ 1:1000, j ∈ 1:1000]
B2 = BitArray(B)
CI = CartesianIndex.(1:1000, 1:1000)
step = size(A,1) +1
    
@btime A[[i == j for i ∈ 1:1000, j ∈ 1:1000]]
2.622 ms (3 allocations: 984.64 KiB)

@btime A[B]
1.806 ms (1 allocation: 7.94 KiB)

@btime A[(1:1000) .== (1:1000)']
509.597 μs (5 allocations: 134.38 KiB)

@btime A[B2]
35.067 μs (1 allocation: 7.94 KiB)

@btime A[[CartesianIndex(i,i) for i in 1:1000]]
6.051 μs (2 allocations: 23.69 KiB)

@btime A[CartesianIndex.(1:1000, 1:1000)]
5.769 μs (2 allocations: 23.69 KiB)

@btime A[CI]
4.093 μs (1 allocation: 7.94 KiB)

@btime A[1:size(A,1)+1:end]
2.123 μs (4 allocations: 8.00 KiB)

@btime A[1:step:end]
2.073 μs (3 allocations: 7.98 KiB)

@btime A[diagind(A)]
2.036 μs (2 allocations: 7.97 KiB)

使用线性索引是最快的解决方案,其中内置的diagind的性能稍好一些.通过CartesianIndices访问对角线元素可能更容易,而且效果仍然很好.

Using linear indices is the fastest solution, where the inbuilt diagind performs slightly better. Accessing out of diagonal elements is probably easier with CartesianIndices and still performs quite good.

这篇关于使用数组进行数组内索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆