Efficiently Swapping Columns in a Matrix
Mostra commenti meno recenti
Is there a more efficient/faster way to switch out two columns in a matrix than calling:
A(:,[i j]) = A(:,[j i]);
If anyone knew of faster implementation (possibly even using MEX), I would greatly appreciate them sharing.
3 Commenti
Sean de Wolski
il 23 Giu 2016
How long is it taking and how fast do you need it to be?
Kyle Marocchini
il 23 Giu 2016
James Tursa
il 23 Giu 2016
Modificato: James Tursa
il 23 Giu 2016
This could easily be done in a mex routine in-place (I can post the code if you want). I don't know how much faster it would run. The caveat is that if A is shared with another variable then you would have unwanted side effects. Do you know if A is shared with any other variable?
Risposta accettata
Più risposte (3)
the cyclist
il 23 Giu 2016
3 voti
Are you certain you actually have to "physically" swap the columns every time? Could you instead simply keep track of the swaps, and then index into the resulting matrix, or do one massive multi-column swap at the end? Just a thought.
2 Commenti
Jos (10584)
il 23 Giu 2016
This a very elegant solution! +1
Kyle Marocchini
il 24 Giu 2016
Modificato: Kyle Marocchini
il 24 Giu 2016
Philip Borghesani
il 23 Giu 2016
Modificato: Philip Borghesani
il 23 Giu 2016
Does your data need to be in a matrix? Swaping two elements of a cell array will be much faster for large element sizes and will be similar to an array list or general list.
%swaptime.m
sz=1e8;
m=ones(sz,5);
for col=1:5
c{col}=ones(sz,1);
end
tic
m(:,[2,5])=m(:,[5,2]);
toc
tic
c([2,5])=c([5,2]);
toc
>> swaptime
Elapsed time is 1.295767 seconds.
Elapsed time is 0.000899 seconds.
Roger Stafford
il 25 Giu 2016
It is possible that matlab accomplishes A(:,[i j]) = A(:,[j i]); by the compiler equivalent of
t1 = A(:,i);
t2 = A(:,j);
A(:,i) = t2;
A(:,j) = t1;
which requires 4*n transfers. If you wrote a mex file that does the equivalent of
t = A(:,i);
A(:,i) = A(:,j);
A(:,j) = t;
it would take only 3*n transfers. I cannot think of any more significant gains that you might make on this kind of swapping. Swapping inherently involves a transfer to temporary storage, transfer of another into the previous location, and finally transfer from temporary storage into the second location.
Categorie
Scopri di più su Matrix Indexing in Centro assistenza e File Exchange
Prodotti
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!