Creating combination matrix of all combinations

7 vues (au cours des 30 derniers jours)
Vick
Vick le 25 Juil 2019
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?

Réponse acceptée

Guillaume
Guillaume le 25 Juil 2019
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

Plus de réponses (0)

Catégories

En savoir plus sur Logical dans Help Center et File Exchange

Tags

Produits


Version

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by