Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Partition Equivalent in Julia

What is an equivalent for Mathematica's Partition function in Julia?

Mathematica's Partition[list,n] takes an array and partitions it into non-overlapping sub-list of length n. On the other hand, the partition function in Julia takes an array and gives all the partitions of that array into n sub-sets.

like image 956
Ali Avatar asked Nov 16 '14 03:11

Ali


3 Answers

Maybe I'm missing something, but doesn't this do what you want?

x = [:a,:b,:c,:d,:e,:f]
n = 2
reshape(x, (n, div(length(x), n)))
like image 68
cd98 Avatar answered Nov 09 '22 15:11

cd98


So in Mathematica:

In[1]:= Partition[{a, b, c, d, e, f}, 2]
Out[1]= {{a,b},{c,d},{e,f}}

but in Julia the partitions function has a very different meaning:

x = [:a,:b,:c,:d,:e,:f]
first(partitions(x,2))
#2-element Array{Array{Symbol,1},1}:
# [:a,:b,:c,:d,:e]
# [:f]

Its the set of all 2-partitions of the set. To get what you want you could do something like

yourpart(x,n) = {{x[i:min(i+n-1,length(x))]} for i in 1:n:length(x)}

and

julia> yourpart([:a,:b,:c,:d,:e,:f], 2)
3-element Array{Any,1}:
 {:a,:b}
 {:c,:d}
 {:e,:f}

julia> yourpart(x,4)
2-element Array{Any,1}:
 {[:a,:b,:c,:d]}
 {[:e,:f]}
like image 11
IainDunning Avatar answered Nov 09 '22 17:11

IainDunning


This also works

partitioneddata=[data[n:n+pfac] for n=1:offset:length(data)-pfac];

where:

  • pfac is how "long" you want your new arrays to each be

and

  • offset is by how many positions you want each new array to be offset by

This can be seen in the following example:

We want to partition [1,2,3,4,5,6,7,8,9,10] into new arrays of length=2 with each array shifted by offset=1.

pfac=2
offset=1
partitioneddata=[data[n:n+pfac] for n=1:offset:length(data)-pfac]
8-element Array{Array{Int64,1},1}: 
[1,2,3]
[2,3,4]
[3,4,5]
[4,5,6]
[5,6,7]
[6,7,8]
[7,8,9]
[8,9,10]

I know I'm a bit late to the party but hopefully this helps!

like image 3
Alejandro Braun Avatar answered Nov 09 '22 16:11

Alejandro Braun