在R中,我可以有条件地分配这样的值:
A = matrix(c(1,2,3,4), ncol = 2)
A =
1 3
2 4
A[,1][A[,2] == 3] = 1000
A =
1000 3
2 4
在朱莉娅,同样的格式不起作用。
A = [1 3; 2 4]
A =
1 3
2 4
A[:,1][A[:,2] .== 3] = 1000
A =
1 3
2 4
我似乎无法弄清楚发生了什么。有人可以帮忙吗?
编辑:谢谢。这适用于将一个值替换为另一个值,例如1和1000.但它不会替换多个值。那是为什么?
>A = [1 3 5; 2 4 6]
>A
1 3 5
2 4 6
>A1 = sub(A, :, 1)
>A1
1
2
>A2 = sub(A, :, 2)
>A2
3
4
>A1[A2 .> 2] = 1000
1000
>A
1000 3 5
2 4 6
为什么替换会在第一个实例停止而不是继续到第二个?
答案 0 :(得分:3)
如链接帖子中所述,范围索引会生成副本。这可以使用SubArray
julia> A = [1 3 5; 2 4 6]
2x3 Array{Int64,2}:
1 3 5
2 4 6
julia> A1 = sub(A, :, 1)
2-element SubArray{Int64,1,Array{Int64,2},Tuple{Colon,Int64},2}:
1
2
julia> A2 = sub(A, :, 2)
2-element SubArray{Int64,1,Array{Int64,2},Tuple{Colon,Int64},2}:
3
4
julia> A1[A2 .== 3] = 1000
1000
julia> A
2x3 Array{Int64,2}:
1000 3 5
2 4 6
或使用for
循环
julia> for i = 1:size(A,1)
A[i,2] == 3 && (A[i,1]=1000)
end
编辑:看起来您看到的奇怪行为已在某个时刻得到修复。这是我在最新的git master上获得的内容
julia> versioninfo()
Julia Version 0.4.0-dev+4743
Commit dc088f7 (2015-05-08 13:29 UTC)
Platform Info:
System: Linux (x86_64-redhat-linux)
CPU: Intel(R) Xeon(R) CPU E5-2630 v2 @ 2.60GHz
WORD_SIZE: 64
BLAS: libopenblas (USE64BITINT DYNAMIC_ARCH NO_AFFINITY Sandybridge)
LAPACK: libopenblas
LIBM: libopenlibm
LLVM: libLLVM-3.3
julia> A = [1 3 5; 2 4 6]
2x3 Array{Int64,2}:
1 3 5
2 4 6
julia> A1 = sub(A, :, 1)
2-element SubArray{Int64,1,Array{Int64,2},Tuple{Colon,Int64},2}:
1
2
julia> A2 = sub(A, :, 2)
2-element SubArray{Int64,1,Array{Int64,2},Tuple{Colon,Int64},2}:
3
4
julia> A2 .> 2
2-element BitArray{1}:
true
true
julia> A1[A2 .> 2]
2-element Array{Int64,1}:
1
2
julia> A1[A2 .> 2] = 1000
1000
julia> A1
2-element SubArray{Int64,1,Array{Int64,2},Tuple{Colon,Int64},2}:
1000
1000
julia> A
2x3 Array{Int64,2}:
1000 3 5
1000 4 6
一般来说,for
循环版本比这样做更快