我有一个关于Julia中布尔比较的简单问题。如何将以下Matlab代码翻译成Julia?
Matlab的:
% create parameters
o = -3;
mat = [65 -4; 65 -3; 65 -2]
% determine which rows of matrix have column 2 less than o AND column 1 equal to 65.
result = (o < mat(:,2) & mat(:,1) == 65)
我在Julia尝试了以下内容:
# create parameters
o = -3
mat = zeros(3,2)
mat[:,1] = 65
mat[1,2] = -4
mat[2,2] = -3
mat[3,2] = -2
mat
# attempt to create desired result
o .< mat[:,2] # this part works
mat[:,1] .== 65 # this part works
test = (o .< mat[:,2] && mat[:,1] .== 65) # doesn't work
test = (o .< mat[:,2] .& mat[:,1] .== 65) # doesn't work
test = (o .< mat[:,2] & mat[:,1] .== 65) # doesn't work
答案 0 :(得分:5)
这是运营商优先权的问题。 &
在Julia中的优先级高于在Matlab中的优先级。只需绕过括号:
test = (o .< mat[:,2]) & (mat[:,1] .== 65)
有关详细信息,请参阅手册中的Noteworthy differences from Matlab(并且还值得阅读其他差异)。
答案 1 :(得分:1)
请注意,您可以在Julia中使用相同的数组创建语法:
julia> mat = [65 -4; 65 -3; 65 -2]
3x2 Array{Int64,2}:
65 -4
65 -3
65 -2
您还可以使用find
获取结果索引的列表:
o = -3
test = (o .< mat[:,2]) & (mat[:,1] .== 65)
julia> find(test)
1-element Array{Int64,1}:
3