Creating combination matrix of all combinations
4 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
Guillaume
2019-7-25
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 个评论
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!