Is the following red expression a good Julia equivalent:
 

julia> a = [ -1 2; 3 -4 ]

 ⋮ 

julia> y = [ 1, 2 ]

 ⋮

julia> [a[i,y[i]] for i=1:2]
2-element Array{Any,1}:
 -1
 -4

(it's also fast)

On Sunday, December 20, 2015 at 2:44:20 AM UTC+2, Lex wrote:
>
> I am expecting [-1 -4] in the Julia example. 
>
> On Saturday, December 19, 2015 at 4:42:07 PM UTC-8, Lex wrote:
>>
>> Hi
>>
>> In Python, I am able to select values like this:
>>
>> >>> a = np.matrix([[-1,2],[3,-4]])
>> >>> y = np.matrix([1,0])
>> >>> a[range(2),y]
>> matrix([[2, 3]])
>> >>>
>>
>> Is there any equivalent in Julia or using a loop is the only way?
>>
>> julia> a
>> 2x2 Array{Int64,2}:
>>  -1   2
>>   3  -4
>>
>> julia> y
>> 1x2 Array{Int64,2}:
>>  1  2
>>
>> julia> a[:, y]
>> ERROR: MethodError: `index_shape_dim` has no method matching 
>> index_shape_dim(::Array{Int64,2}, ::Int64, ::Array{Int64,2})
>>
>> You might have used a 2d row vector where a 1d column vector was required.
>> Note the difference between 1d column vector [1,2,3] and 2d row vector [1 
>> 2 3].
>> You can convert to a column vector with the vec() function.
>> Closest candidates are:
>>   index_shape_dim(::Any, ::Any, ::Real...)
>>   index_shape_dim(::Any, ::Any, ::Colon)
>>   index_shape_dim(::Any, ::Any, ::Colon, ::Any, ::Any...)
>>   ...
>>  in getindex at abstractarray.jl:488
>>
>> julia> a[:, y[]]
>> 2-element Array{Int64,1}:
>>  -1
>>   3
>>
>> julia> a[:, y[:]]
>> 2x2 Array{Int64,2}:
>>  -1   2
>>   3  -4
>>
>> julia>
>>
>>
>>

Reply via email to