Star
Star

Reputation: 2299

Create all possible n-tuples from n vectors in Matlab, ordered in a specific way

Consider n row vectors in Matlab, each of size 1xU. For example,

U=20;
n=3;
sU=[U U U];
vectors = arrayfun(@(x) {1:x}, sU); 

where vector{1} is the first row vector, vector{2} is the second row vector,..., vector{n} is the last row vector.

We create the matrix Tcoord of size U^n x n reporting all the possible n-tuples from the n row vectors. For each row i of Tcoord, Tcoord(i,1) is an element of the first row vector, Tcoord(i,2) is an element of the second row vector, ... , Tcoord(i,n) is an element of the last row vector.

Tcoord_temp = cell(1,n);
[Tcoord_temp{:}] = ndgrid(vectors{:}); 
Tcoord_temp = cat(n+1, Tcoord_temp{:});
Tcoord = reshape(Tcoord_temp,[],n); 

Suppose now that I augment each of the n row vectors of 3 elements. For example,

vectors_augmented{1}=[vectors{1} 8 9 10];
vectors_augmented{2}=[vectors{2} 11 12 13];
vectors_augmented{3}=[vectors{3} 14 15 16];

I then create a matrix similar to Tcoord but now using vectors_augmented.

Tcoord_temp = cell(1,n);
[Tcoord_temp{:}] = ndgrid(vectors_augmented{:}); 
Tcoord_temp = cat(n+1, Tcoord_temp{:});
Tcoord_augmented = reshape(Tcoord_temp,[],n); %(U+3)^nxn

I would like your help to re-order the rows of the matrix Tcoord_augmented in a matrix Tcoord_augmented_reshape such that

Upvotes: 0

Views: 153

Answers (1)

Luis Mendo
Luis Mendo

Reputation: 112759

The simplest approach is to build an auxiliary zero-one matrix the same size as Tcoord_augmented and sort rows based on that:

aug_size = [3 3 3]; % augment size of each vector. Not necessarily equal
vectors_aux = arrayfun(@(a) {[false(1,U) true(1, a)]}, aug_size);
T_aux = cell(1,n);
[T_aux{:}] = ndgrid(vectors_aux{:}); 
T_aux = cat(n+1, T_aux{:});
T_aux = reshape(T_aux,[],n); 
[~, ind] = sortrows(T_aux, n:-1:1); % indices of stably sorting the rows.
% Most significant column is rightmost, as per your code
Tcoord_augmented_reorder = Tcoord_augmented(ind, :);

Upvotes: 1

Related Questions