All possible combinations of 2 vectors.

7 views (last 30 days)
Artyom on 22 Nov 2012
Hi everyone.
I have one vector and one number. For example [1 3 5] and 0.
How do I generate all possible combinations? Like this:
0 3 5
1 0 5
1 3 0
0 0 5
0 3 0
1 0 0
0 0 0
Artyom on 22 Nov 2012
The rule is:
1) we have an n - dimensional vector.
2) replace one number with zero and find all combinations
3) replace two numbers with zero and find all combinations
4) ...
5) replace n-1 number with zero and find all combinations
6) replace n number with zero

Matt Fig on 22 Nov 2012
Edited: Matt Fig on 23 Nov 2012
Here is a solution:
function H = mycomb(V)
% Help
L = length(V);
H = cell(1,L);
for ii = 1:L-1
C = nchoosek(1:L,L-ii);
R = cumsum(ones(size(C)));
M = max(R(:,1));
H{ii} = zeros(M,L);
H{ii}(R+(C-1)*M) = V(C);
end
H{L} = zeros(1,L);
H = vertcat(H{:});
Now try it out from the command line:
>> mycomb([4 5 6])
ans =
4 5 0
4 0 6
0 5 6
4 0 0
0 5 0
0 0 6
0 0 0
>> mycomb([4 5 6 7])
ans =
4 5 6 0
4 5 0 7
4 0 6 7
0 5 6 7
4 5 0 0
4 0 6 0
4 0 0 7
0 5 6 0
0 5 0 7
0 0 6 7
4 0 0 0
0 5 0 0
0 0 6 0
0 0 0 7
0 0 0 0

Andrei Bobrov on 22 Nov 2012
Edited: Andrei Bobrov on 22 Nov 2012
variant
t = [1 3 5];
ii = perms([t, zeros(size(t))]);
out = unique(sort(t(:,1:numel(t)),2),'rows');
or
t = [1 3 5];
out = [];
n = numel(t);
for jj = 1:n
k = nchoosek(t,n - jj);
out = [out;[zeros(size(k,1),jj),k]];
end
or
k = ones(1,numel(t)) * 2.^(numel(t)-1:-1:0)';
out = bsxfun(@times,t,dec2bin(0:k - 1,numel(t))-'0');
Matt Fig on 23 Nov 2012
Very nice! (The last one)

Azzi Abdelmalek on 22 Nov 2012
Edited: Azzi Abdelmalek on 23 Nov 2012
save this function
function y=arrangement(v,n)
m=length(v);
y=zeros(m^n,n);
for k = 1:n
y(:,k) = repmat(reshape(repmat(v,m^(n-k),1),m*m^(n-k),1),m^(k-1),1);
end
then type
x=arrangement([1 3 5 0],3)
out=x(~all(x,2),:)
If you don't need repetition add
s=arrayfun(@(t) sort(out(t,:)),(1:size(out,1))','un',0)
out1=unique(cell2mat(s),'rows')

Matt J on 23 Nov 2012
Edited: Matt J on 23 Nov 2012
t=[1 3 5];
n=length(t);
result = bsxfun(@times, [1,3,5], dec2bin(2^n-1:-1:0)-'0')

Categories

Find more on Graphics Object Programming 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!

Translated by
{"found_math": false, "script_math_tex": 0, "script_math_asciimath": 0, "math_annotations": 0, "math_alttext": 0, "mathml": 0, "mathjax_tag": 0, "mathjax_inline_tex": 0, "mathjax_display_tex": 0, "mathjax_asciimath": 0, "img_math": 0, "codecogs_latex": 0, "wp_latex": 0, "mimetex.cgi": 0, "/images/math/codecogs": 0, "mathtex.cgi": 0, "katex": 0, "math-container": 0, "wp-katex-eq": 0, "align": 0, "equation": 0, "x-ck12": 0, "texerror": 0}