Permutations with repetition of vectors in different matrices
3 views (last 30 days)
Show older comments
I'd like to know how combine different vector in order to obtain different matrix. I explain it with an exemple. I have four vectors a=[15 30 45]; b=[1 65 8]; c=[70 13 95] and d=[3 61 93]. I want to combine this four vectors in order to obtain 64 matrices (permutations with repetition: 4^3) with three rows or a 3D matrix. M1=[a;a;a] M1=[a;a;b] M1=[a;a;c] M1=[a;a;d] M1=[a;b;a] M1=[a;b;b] M1=[a;b;c] ... Does anyone know if there is a specific function or can anyone help me to create a matlab code in order to do it?
0 Comments
Accepted Answer
Guillaume
on 30 Mar 2015
A fairly simple way is to put your different vectors into a matrix and use dec2base to generate the 64 different row indices for that matrix:
a = [15 30 45];
b = [1 65 8];
c = [70 13 95];
d = [3 61 93];
srcvec = [a; b; c; d];
rowchoices = dec2base(0:4^3-1, 4) - '0' + 1;
veccomb = cellfun(@(c) srcvec(c, :), num2cell(rowchoices, 2), 'UniformOutput', false);
veccomb = cat(3, veccomb{:})
3 Comments
Guillaume
on 30 Mar 2015
Yes, you only have to change rowchoices. However, it will only work for up to 10 vectors. After that dec2bin will start to use letters, so the - '0' to convert the ascii values of '0' to '9' into their respective numbers won't work any more.
With a bit more sophistication, you could get it to work up to 36, which is the maximum base supported by dec2base.
More Answers (1)
Stephen23
on 30 Mar 2015
Edited: Stephen23
on 31 Mar 2015
This simple code will generate a matrix with all of the permutations of 3 chosen from 1:4 with replacement:
N = 3;
[Y{N:-1:1}] = ndgrid(1:4);
Y = reshape(cat(N+1,Y{:}),[],N);
>> Y
Y =
1 1 1
1 1 2
1 1 3
1 1 4
1 2 1
1 2 2
...
4 4 1
4 4 2
4 4 3
4 4 4
You can use these as indices to extract the elements from each vector:
X = [a; b; c; d];
Z = cellfun(@(y)X(y,:), num2cell(Y,2), 'UniformOutput', false);
Z = cat(3,Z{:});
0 Comments
See Also
Categories
Find more on Characters and Strings in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!