Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Julia language: sub vs. slice function

Could someone explain in simple terms the difference between julia's v0.4 function:

sub and slice (and maybe slicedim)

Some simple example would be greatly appriciated. Thanks a lot

like image 312
user3426681 Avatar asked Mar 21 '15 16:03

user3426681


People also ask

How does Julia define vector?

A Vector in Julia can be created with the use of a pre-defined keyword Vector() or by simply writing Vector elements within square brackets([]). There are different ways of creating Vector.

How do you create an array of zeros in Julia?

This is usually called with the syntax Type[] . Element values can be specified using Type[a,b,c,...] . zeros([T=Float64,] dims::Tuple) zeros([T=Float64,] dims...) Create an Array , with element type T , of all zeros with size specified by dims .


1 Answers

The difference is that slice drops all dimensions "sliced" with a scalar (non-vector), while sub often retains them. For example:

julia> A = rand(3,3)
3x3 Array{Float64,2}:
 0.403464   0.229403  0.924686
 0.953741   0.175086  0.49139 
 0.0290678  0.705564  0.567355

julia> a = slice(A, 2, :)   # this will be 1-dimensional
3-element SubArray{Float64,1,Array{Float64,2},(Int64,Colon),2}:
 0.953741
 0.175086
 0.49139 

julia> b = sub(A, 2, :)     # this will be 2-dimensional
1x3 SubArray{Float64,2,Array{Float64,2},(UnitRange{Int64},Colon),2}:
 0.953741  0.175086  0.49139

julia> size(a)
(3,)

julia> size(b)
(1,3)

There's one exception: sub drops dimensions indexed with a scalar if they are "trailing" dimensions, meaning there are no later dimensions indexed with a vector:

julia> a = slice(A, :, 2)
3-element SubArray{Float64,1,Array{Float64,2},(Colon,Int64),2}:
 0.229403
 0.175086
 0.705564

julia> b = sub(A, :, 2)
3-element SubArray{Float64,1,Array{Float64,2},(Colon,Int64),2}:
 0.229403
 0.175086
 0.705564

julia> size(a)
(3,)

julia> size(b)
(3,)

If you slice with a range, then you get behavior like sub:

julia> a = slice(A, 2:2, :)
1x3 SubArray{Float64,2,Array{Float64,2},(UnitRange{Int64},Colon),1}:
 0.953741  0.175086  0.49139

julia> size(a)
(1,3)

It's not the length of the index that matters, it's the type: any dimension indexed with a non-scalar will be retained.

like image 186
tholy Avatar answered Oct 21 '22 04:10

tholy