Array is a collection of elements stored
in multi dimensional grid, unlike other languages all the elements in array need
not to be of same type.
julia> arr1=[2, "Hi", 23.5] 3-element Array{Any,1}: 2 "Hi" 23.5 julia> typeof(arr1) Array{Any,1}
‘,’ is not necessary while defining an
array. You can define array using space(Instead of separating elements by ,)
also.
julia> arr1=[1 2 3] 1x3 Array{Int64,2}: 1 2 3
Get
number of elements in array
length(A) function is used to get number
of elements in array A.
julia> length(arr1) 3
Get
type of elements contained in array
eltype(A) return the type of elements
contained in array A.
julia> arr2=[1, 2, "Hi", 23.456] 4-element Array{Any,1}: 1 2 "Hi" 23.456 julia> eltype(arr2) Any julia> arr3=["Hi" "How" "are" "you"] 1x4 Array{ASCIIString,2}: "Hi" "How" "are" "you" julia> eltype(arr3) ASCIIString
Accessing
elements of array
You can access elements of array using
index notation. A[1] is used to access first element of array A, A[2] is used
to access 2nd element of array A, A[end] is used to access the last
element of array A.
julia> arr3 1x4 Array{ASCIIString,2}: "Hi" "How" "are" "you" julia> arr3[1] "Hi" julia> arr3[end] "you" julia> arr3[end-1] "are"
Iterate
over array
eachindex(A) returns an iterator to
iterate over each position in the array.
julia> for i in eachindex(arr3) println(i," ", arr3[i]) end 1 Hi 2 How 3 are 4 you
Pass
by reference
In Julia, arrays are passed to functions
by reference, so any changes made to the array inside the function are
available outside the function also.
julia> function addXtoArray(arr, a) for i in eachindex(arr) arr[i] += a end end addXtoArray (generic function with 1 method) julia> arr1=[2, 3, 5, 7, 11] 5-element Array{Int64,1}: 2 3 5 7 11 julia> addXtoArray(arr1, 5) julia> arr1 5-element Array{Int64,1}: 7 8 10 12 16
No comments:
Post a Comment