Creating combination matrix of all combinations
7 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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?
0 commentaires
Réponse acceptée
Guillaume
le 25 Juil 2019
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 commentaires
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Logical dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!