Julia矩阵中根据行名和列名提取子矩阵

R语言中, 矩阵可以设置行名和列名, 然后根据行名和列名进行提取.

R语言代码:

R_test = matrix(1:16,4,4)
colnames(R_test) = rownames(R_test) = c("A","B","C","D")
R_test

id2 = c("B","C")
R_test[id2,id2]

结果如下:

> R_test = matrix(1:16,4,4)
> colnames(R_test) = rownames(R_test) = c("A","B","C","D")
> R_test
  A B  C  D
A 1 5  9 13
B 2 6 10 14
C 3 7 11 15
D 4 8 12 16
> 
> id2 = c("B","C")
> R_test[id2,id2]
  B  C
B 6 10
C 7 11

在Julia中解决方法如下:

思路如下:

  • 1, 原始的行名和列名ID1
  • 2, 需要提取的行名和列名ID2
  • 3, 因为Array都是从1开始的数字编号, 所以构建一个Dict, 将ID1作为keys, 将数字编号作为values
  • 4, 将ID2作为keys, 提取对应的数字编号values, 命名为re
  • 5, 使用ID2对应的re提取矩阵的子矩阵.
  • 代码如下:
julia_test = reshape(collect(1:16),4,4)
id1 =["a","b","c","d"]
j =1
tt = Dict()
for i in id1
    get!(tt,i,j)
    j = j+1
end
tt
id2 = ["b","c"]
re =[]
for i in id2
    push!(re,tt[i])
end
re
julia_test[re,re]

结果如下:

Main> julia_test = reshape(collect(1:16),4,4)
4×4 Array{Int64,2}:
 1  5   9  13
 2  6  10  14
 3  7  11  15
 4  8  12  16

Main> id1 =["a","b","c","d"]
4-element Array{String,1}:
 "a"
 "b"
 "c"
 "d"

Main> j =1
1

Main> tt = Dict()
Dict{Any,Any} with 0 entries

Main> for i in id1
           get!(tt,i,j)
           j = j+1
       end

Main> tt
Dict{Any,Any} with 4 entries:
  "c" => 3
  "b" => 2
  "a" => 1
  "d" => 4

Main> id2 = ["b","c"]
2-element Array{String,1}:
 "b"
 "c"

Main> re =[]
0-element Array{Any,1}

Main> for i in id2
           push!(re,tt[i])
       end

Main> re
2-element Array{Any,1}:
 2
 3

Main> julia_test[re,re]
2×2 Array{Int64,2}:
 6  10
 7  11

问题解决.

参考:

  1. http://discourse.juliacn.com/t/topic/811?u=yijiaobani

猜你喜欢

转载自blog.csdn.net/yijiaobani/article/details/82851132