Concatenating two collections into a new one

question

#1

Hi,

I am trying to concatenate two collections of which each element is an object of a custom type resulting in a new collection. Is there any function which will do this for me ? E.g. I found union(c1, c2) which roughly does the job but I am interested in pure concatenation. I also found append!(c1, c2) which actually does the job but c1 get overwritten.

Thanks,
Jan


#2

If you don’t want c1 to be overwritten, can you deepcopy it?

c = deepcopy(c1)
append!(c, c2)

#3

What do you mean by that?

Do not use deepcopy for this. copy might be ok.


#4

union is meant to be used with sets, it will get rid of any duplicated (non-unique) elements. vcat is probably what you want.


#5

pure concatenation

union(c1, c2) would repeat any element which is in c1 and also in c2 only once e.g.

c1 = ["a","b","c"]
c2 = ["b","c","d"]
union(c1, c2)
4-element Array{String,1}:
 "a"
 "b"
 "c"
 "d"

however the following concatenation return full 6-element array

[c1; c2]

6-element Array{String,1}:
 "a"
 "b"
 "c"
 "b"
 "c"
 "d"

This is the desired behaviour. I wondered whether there is a general function for concatenating two general collections. I will try:

cat(1, c1, c2)

and post results later.

Using copy() (or deepcopy()) and append!() would indeed work.

Thanks,
Jan


#6

Yes, indeed, vcat() seems like a solution. I’ll give it a shot tomorrow.

Thanks,
Jan


#7

OK, it wasn’t clear from your original post what collection are you talking about. If you just mean Vectors then vcat is what you need. Note that it is exactly the same as [a; b].


#8

Thanks for all the helpful answers. I should have started with an example :). vcat() works well :

type myType
    name::String
    a::Int
end

c1 = [ myType("a" * string(i), i) for i in rand(91:100, 5) ]
c2 = [ myType("a" * string(i), i) for i in rand(81:100, 5) ]

c1
5-element Array{myType,1}:
 myType("a91",91)
 myType("a98",98)
 myType("a95",95)
 myType("a91",91)
 myType("a92",92)

c2
5-element Array{myType,1}:
 myType("a90",90)
 myType("a95",95)
 myType("a86",86)
 myType("a87",87)
 myType("a81",81)

vcat(c1, c2)
10-element Array{myType,1}:
 myType("a91",91)
 myType("a98",98)
 myType("a95",95)
 myType("a91",91)
 myType("a92",92)
 myType("a90",90)
 myType("a95",95)
 myType("a86",86)
 myType("a87",87)
 myType("a81",81)

I ruled out vcat() because I thought for some reason it is not applicable to collections. What is in general a difference between an array and a collection ?

Thanks,
Jan


#9

Array (and therefore Vector and Matrix) is a particular kind of AbstractArray, which is itself a particular kind of collection. Other collections include Set, Dict, Tuple and String.


#10

Thanks a lot for clarification.

Jan