MATLAB: All possible combinations of 2 vectors.

combinations

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

Best Answer

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