Generate a matrix containing all combinations of elements from n vectors (Cartesian product)

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

C++ Matrix Class

nota bene. This answer has 20 upvotes now, but it is not intended as an endorsement of std::valarray. In my experience, time is better spent installing and learning to use a full-fledged math library such as Eigen. Valarray has fewer features than the competition, but it isn’t more efficient or particularly easier to use. If … Read more

Matrix “Zigzag” Reordering

Consider the code: M = randi(100, [3 4]); %# input matrix ind = reshape(1:numel(M), size(M)); %# indices of elements ind = fliplr( spdiags( fliplr(ind) ) ); %# get the anti-diagonals ind(:,1:2:end) = flipud( ind(:,1:2:end) ); %# reverse order of odd columns ind(ind==0) = []; %# keep non-zero indices M(ind) %# get elements in zigzag order … Read more