问题描述
让我们考虑 5 x 5 晶格,每个点的索引为 (1,1),(1,2),...(1,5),(2,1),...,(5,5),并将这个格子称为 L
.
Let us consider 5 x 5 lattice with each point indexed as (1,1),(1,2),...(1,5),(2,1),...,(5,5), and call this lattice L
.
我想制作一个 5 x 5 矩阵,每个元素都有一个值,该值指示 L
的每个点,如下所示:
I want to make a 5 x 5 matrix with each element having a value which indicates each point of L
like this:
5×5 Matrix{Vector{Int64}}:
[1, 1] [1, 2] [1, 3] [1, 4] [1, 5]
[2, 1] [2, 2] [2, 3] [2, 4] [2, 5]
[3, 1] [3, 2] [3, 3] [3, 4] [3, 5]
[4, 1] [4, 2] [4, 3] [4, 4] [4, 5]
[5, 1] [5, 2] [5, 3] [5, 4] [5, 5]
我尝试了什么
我刚刚尝试了以下方法:
What I tried
I just tried the following:
X1 = [1,2,3,4,5]
X2 = copy(X1)
Lattice = Matrix{Vector{Int64}}(undef, length(X1), length(X2)) # what I want to make
for x1 in X1
for x2 in X2
Lattice[x1,x2] = [X1[x1],X2[x2]]
end
end
Lattice
问题
- 还有其他方法可以使代码简单或简短吗?
- 如果增加像 50 x 50 这样的晶格尺寸,我担心性能会变差.还有更好的方法吗?
- 有什么更好的做法?
任何信息将不胜感激.
推荐答案
它不是向量矩阵,但 CartesianIndices 服务于这个目的.
It's not a Matrix of Vectors, but CartesianIndices serves this purpose.
L = zeros((5,5)) # example 5x5 Matrix
Li = CartesianIndices(size(L))
#=
5×5 CartesianIndices{2,Tuple{Base.OneTo{Int64},Base.OneTo{Int64}}}:
CartesianIndex(1, 1) … CartesianIndex(1, 5)
CartesianIndex(2, 1) CartesianIndex(2, 5)
CartesianIndex(3, 1) CartesianIndex(3, 5)
CartesianIndex(4, 1) CartesianIndex(4, 5)
CartesianIndex(5, 1) CartesianIndex(5, 5)
=#
如果您必须拥有像您的帖子中那样的索引矩阵,您可以创建一个将 CartesianIndex 转换为 Vector 并通过 CartesianIndices 广播该方法的方法:
If you must have the indices matrix like in your post, you could make a method that converts a CartesianIndex to a Vector and broadcast that method over the CartesianIndices:
CItoVector(CI) = collect(Tuple(CI))
CItoVector.(Li)
#=
5×5 Array{Array{Int64,1},2}:
[1, 1] [1, 2] [1, 3] [1, 4] [1, 5]
[2, 1] [2, 2] [2, 3] [2, 4] [2, 5]
[3, 1] [3, 2] [3, 3] [3, 4] [3, 5]
[4, 1] [4, 2] [4, 3] [4, 4] [4, 5]
[5, 1] [5, 2] [5, 3] [5, 4] [5, 5]
=#
但我建议坚持使用 CartesianIndices,因为它不分配内存,而且 CartesianIndex 是为数组索引量身定制的,这似乎是您的意图.
But I recommend sticking with CartesianIndices because it doesn't allocate memory, and CartesianIndex is tailor-made for array indexing, which seems to be your intent.
这篇关于在 Julia 中制作二维晶格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!