Modify arrays in function

How to modify array t=[1,2,3] in function like
function dosth!( arg )
. . .
end
In body i wanna in first case change my array to empty(arg = [ ] ), in second case change table something like ( arg = arg[2:end] )

After using function result should be

  1. 0-element Array{Any,1}
  2. 2-element Array{Int64,1}:

You can empty an array with the empty!() function:

julia> t = [1, 2, 3]
3-element Array{Int64,1}:
 1
 2
 3

julia> empty!(t)
0-element Array{Int64,1}

julia> t
0-element Array{Int64,1}

and you can delete an element of an array with deleteat!():

julia> t = [1, 2, 3]
3-element Array{Int64,1}:
 1
 2
 3

julia> deleteat!(t, 1)
2-element Array{Int64,1}:
 2
 3

julia> t
2-element Array{Int64,1}:
 2                                                                                                                                                                                                                                                                                                                                    
 3  

Or, more efficiently, by using popfirst! if you want to delete the first element:

julia> t = [1, 2, 3]
3-element Array{Int64,1}:
 1
 2
 3

julia> popfirst!(t)
1

julia> t
2-element Array{Int64,1}:
 2
 3
2 Likes

And if I want to do it without embedded function?
Something more linke in MATLAB? It’s bad way manipulate in range [ from : to ]. It’s possible?

something like this?

t = [4,5,6]
t=t[2:end] # [5,6]
t=t[[1,3]] #[4,6], first and third elements 

you can do it, it’s not the most performant way (it copies the array), but it’s possible

There’s an important difference: popfirst!(t) modifies the array itself, while t = t[2:3] creates a completely new array and then assigns the name t to that new array. In one case the modification will be visible outside of the function and in the other case it will not.

3 Likes