Cartesian product in MATLAB

荒凉一梦 提交于 2019-12-18 03:12:13

问题


Here is the simplified version of the problem I have. Suppose I have a vector

p=[1 5 10]

and another one

q=[.75 .85 .95].

And I want to come up with the following matrix:

res=[1, .75;1, .85; 1, .95; 5, .75; 5, .85; 5, .95; 10, .75; 10, .85; 10, .95].

This is also known as the Cartesian Product. How can I do that?

Many thanks


回答1:


Here's one way:

[X,Y] = meshgrid(p,q);
result = [X(:) Y(:)];

The output is:

result =

    1.0000    0.7500
    1.0000    0.8500
    1.0000    0.9500
    5.0000    0.7500
    5.0000    0.8500
    5.0000    0.9500
   10.0000    0.7500
   10.0000    0.8500
   10.0000    0.9500



回答2:


A similar approach as the one described by @nibot can be found in matlab central file-exchange.

It generalizes the solution to any number of input sets. This would be a simplified version of the code:

function C = cartesian(varargin)
    args = varargin;
    n = nargin;

    [F{1:n}] = ndgrid(args{:});

    for i=n:-1:1
        G(:,i) = F{i}(:);
    end

    C = unique(G , 'rows');
end

For instance:

cartesian(['c','d','e'],[1,2],[50,70])

ans =

    99     1    50
    99     1    70
    99     2    50
    99     2    70
   100     1    50
   100     1    70
   100     2    50
   100     2    70
   101     1    50
   101     1    70
   101     2    50
   101     2    70


来源:https://stackoverflow.com/questions/9834254/cartesian-product-in-matlab

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!