Reputation: 1017
I have a simple question about boolean comparisons in Julia. How do I translate the following Matlab code to 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)
I've tried the following in 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
Upvotes: 9
Views: 1553
Reputation: 31372
It's a matter of operator precedence. &
has a higher precedence in Julia than it does in Matlab. Just shift around your parentheses:
test = (o .< mat[:,2]) .& (mat[:,1] .== 65)
See Noteworthy differences from Matlab in the manual for more details (and it's worth reading through the other differences, too).
Upvotes: 8
Reputation: 5325
Note that you can use the same array creation syntax in Julia:
julia> mat = [65 -4; 65 -3; 65 -2]
3x2 Array{Int64,2}:
65 -4
65 -3
65 -2
You can also use find
to get a list of the resulting indices:
o = -3
test = (o .< mat[:,2]) & (mat[:,1] .== 65)
julia> find(test)
1-element Array{Int64,1}:
3
Upvotes: 1