On Thursday, March 12, 2015 at 10:08:47 AM UTC-4, Ján Dolinský wrote:
>
> Hi,
>
> Is this an efficient way to swap two columns of a matrix ?
> e.g. 1st column with the 5th
>
> X = rand(10,5)
> X[:,1], X[:,5] = X[:,5], X[:,1]
>
It is not optimal, because it allocates temporary arrays. Instead, you can
just write:
function swapcols(X, i, j)
for k = 1:size(X,1)
X[k,i],X[k,j] = X[k,j],X[k,i]
end
return X
end
which allocates no temporary arrays and should be quite efficient. You
could gain a bit more efficiency by moving all of the bounds checks outside
of the loop:
function swapcols(X, i, j)
m, n = size(X)
if (1 <= i <= n) && (1 <= j <= n)
for k = 1:m
@inbounds X[k,i],X[k,j] = X[k,j],X[k,i]
end
return X
else
throw(BoundsError())
end
end
but these kinds of micro-optimizations are rarely worthwhile.