Creating combination matrix of all combinations

4 visualizaciones (últimos 30 días)
Vick
Vick el 25 de Jul. de 2019
Respondida: Guillaume el 25 de Jul. de 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?

Respuesta aceptada

Guillaume
Guillaume el 25 de Jul. de 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

Más respuestas (0)

Categorías

Más información sobre Creating and Concatenating Matrices en Help Center y File Exchange.

Etiquetas

Productos


Versión

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by