Tips & Tricks

Matt J

How to randomly permute a vector without calling numel(), length(), or size()

Matt J on 5 Mar 2024 (Edited on 5 Mar 2024)
Latest activity Edit by Stephen23 on 11 Mar 2024

Given a vector v whose order we would like to randomly permute, many would perform the permutation by explicitly querying the length/size of v, e.g.,
However, one can instead do as follows, avoiding the size query.
Analogous things can be done with matrices, e.g.,
A=A(randperm(end), randperm(end));
Stephen23 on 5 Mar 2024 (Edited on 11 Mar 2024)
@Matt J: that is a very useful tip.
Note that END can be supplied as an input to any function, as long as it is used within some indexing. I often use this with MAX() and MIN() to avoid indexing errors, e.g.:
B = A(1:min(end,9))
Adam Danz
Adam Danz on 5 Mar 2024

Terrific trick!

See Also


No tags entered yet.