permuting rows of a matrix

758 views
Skip to first unread message

Davide Lasagna

unread,
Mar 11, 2015, 8:49:47 AM3/11/15
to julia...@googlegroups.com
Hi, 


permute!(v, p) permutes the elements of v according to the permutation vector p.

Is there any equivalent built in function for permuting rows of a matrix? Given the memory layout of julia matrices it should not be too difficult to have a similar function for matrices as well.

Thanks, 

Davide

Mauro

unread,
Mar 11, 2015, 9:38:34 AM3/11/15
to julia...@googlegroups.com
Have a look at the permute! function in julia:
@less permute!([1,2], [1,2])

Modifying it to

function permute!!{T<:Integer}(a, i, p::AbstractVector{T})
count = 0
start = 0
while count < length(a)
ptr = start = findnext(p, start+1)
temp = a[i,start]
next = p[start]
count += 1
while next != start
a[i,ptr] = a[i,next]
p[ptr] = 0
ptr = next
next = p[next]
count += 1
end
a[i,ptr] = temp
p[ptr] = 0
end
a
end

should work (untested). Note that permuting a column should be faster
though as julia matrices are column-major.

Davide Lasagna

unread,
Mar 11, 2015, 9:49:09 AM3/11/15
to julia...@googlegroups.com
Thanks, I will have a look at this.

Is there some interest to have this in base?

Davide

Tim Holy

unread,
Mar 11, 2015, 10:02:31 AM3/11/15
to julia...@googlegroups.com
A[p, :]

--Tim

Davide Lasagna

unread,
Mar 11, 2015, 10:09:38 AM3/11/15
to julia...@googlegroups.com
But A[p, :] makes copies, and I want it to be in place.

Davide

Tim Holy

unread,
Mar 11, 2015, 10:42:38 AM3/11/15
to julia...@googlegroups.com
Good that you clarified that, but are you aware that permute! makes a copy of
the permutation? So there's no memory savings, and it's about 4x slower than
an out-of-place copy.

--Tim

Davide Lasagna

unread,
Mar 11, 2015, 10:49:34 AM3/11/15
to julia...@googlegroups.com
Well, thanks Tim for pointing this out.

Cheers, 

Davide

Kevin Squire

unread,
Mar 11, 2015, 12:53:11 PM3/11/15
to julia...@googlegroups.com
If you don't mind losing the original permutation (it's overwritten), you can use Base.permute!! (unexported).  However, in most cases, this is still actually slower than A[p].  Not sure how that would be for sorting rows/columns.

Kevin
Reply all
Reply to author
Forward
0 new messages