Generate a matrix containing all combinations of elements taken from n vectors

The ndgrid function almost gives the answer, but has one caveat: n output variables must be explicitly defined to call it. Since n is arbitrary, the best way is to use a comma-separated list (generated from a cell array with ncells) to serve as output. The resulting n matrices are then concatenated into the desired … Read more

Parfor for Python

The one built-in to python would be multiprocessing docs are here. I always use multiprocessing.Pool with as many workers as processors. Then whenever I need to do a for-loop like structure I use Pool.imap As long as the body of your function does not depend on any previous iteration then you should have near linear … Read more

find length of sequences of identical values in a numpy array (run length encoding)

Fully numpy vectorized and generic RLE for any array (works with strings, booleans etc too). Outputs tuple of run lengths, start positions, and values. import numpy as np def rle(inarray): “”” run length encoding. Partial credit to R rle function. Multi datatype arrays catered for including non Numpy returns: tuple (runlengths, startpositions, values) “”” ia … Read more

Faster way to initialize arrays via empty matrix multiplication? (Matlab)

This is strange, I am seeing f being faster while g being slower than what you are seeing. But both of them are identical for me. Perhaps a different version of MATLAB ? >> g = @() zeros(1000, 0) * zeros(0, 1000); >> f = @() zeros(1000) f = @()zeros(1000) >> timeit(f) ans = 8.5019e-04 … Read more