Creating combination matrix of all combinations

7 ビュー (過去 30 日間)
Vick
Vick 2019 年 7 月 25 日
回答済み: Guillaume 2019 年 7 月 25 日
Hi,
I've two or more variable and i've to form a combination matrix out of it. For example,
I've 2 variables say a=[1,2,3,4];b=[5,6,7,8];
now I've to form the combinations of their operation,Like
out=[];
for i=1:length(a)
for j=1:length(b)
out(end+1,1:2)=[a(i),b(j)];
end
end
But the above program works for only 2 variables. How to write a code which works for nay number of variables?

採用された回答

Guillaume
Guillaume 2019 年 7 月 25 日
Use ndgrid and expansion of cell arrays into comma-separated lists :
function c = cartprod(varargin)
%c = allcomb(v1, v2, ....) create a matrix of the cartesian product of all vector
%v1, v2,... must be numeric vectors
%c(r, :) is a unique combination of the elements of v1, v2, ...
%c is size numel(v1)*numel(v2)*... x N (N: number of input vectors).
%TODO: add input validation
c = cell(size(varargin)); %create cell array to store output of ndgrid
[c{:}] = ndgrid(varargin{:}); %expand varargin into c-s-l and store output in c. C{i} is N-d array (N = number of vectors)
c = cat(numel(varargin) + 1, c{:}); %concatenate the N-d arrays into a N+1-d array
c = reshape(c, [], numel(varargin)); %and reshape into ?xN matrix
end

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

タグ

製品


リリース

R2018a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by