【问题标题】:All combinations for matrix in matlabmatlab中矩阵的所有组合
【发布时间】:2012-11-25 11:59:08
【问题描述】:

我正在尝试查找 n×n 矩阵的所有组合而不重复。

例如,我有一个这样的矩阵:

A = [321 319 322; ...
     320 180 130; ...
     299 100 310];

我想要以下结果:

(321 180 310)
(321 130 100)
(319 320 310)
(319 139 299)
(322 320 100)
(322 180 299)

我尝试过使用ndgrid,但它占用了行或列两次。

【问题讨论】:

标签: matlab matrix combinations


【解决方案1】:

这是一个更简单的(本机)解决方案,带有 permsmeshgrid

N = size(A, 1);
X = perms(1:N);                    % # Permuations of column indices
Y = meshgrid(1:N, 1:factorial(N)); % # Row indices
idx = (X - 1) * N + Y;             % # Convert to linear indexing
C = A(idx)                         % # Extract combinations

结果是一个矩阵,每一行包含不同的元素组合:

C =

   321   180   310
   319   320   310
   321   130   100
   319   130   299
   322   320   100
   322   180   299

这个解决方案也可以简写为:

C = A((perms(1:N) - 1) * N + meshgrid(1:N, 1:factorial(N)))

【讨论】:

    【解决方案2】:

    ALLCOMB是你问题的关键

    例如我不在 MATLAB 机器前,所以我从网上获取了一个示例。

    x = allcomb([1 3 5],[-3 8],[],[0 1]) ;
    ans
    1 -3 0
    1 -3 1
    1 8 0
    ...
    5 -3 1
    5 8 0
    5 8 1
    

    【讨论】:

    • 如果将allcomb的参数作为给定矩阵的行输入,则会导致列重复,这不是必需的。
    【解决方案3】:

    您可以使用perms 来排列列,如下所示:

    % A is given m x n matrix
    row = 1:size( A, 1 );
    col = perms( 1:size( A, 2 ) );
    
    B = zeros( size( col, 1 ), length( row )); % Allocate memory for storage
    
    % Simple for-loop (this should be vectorized)
    % for c = 1:size( B, 2 )
    %     for r = 1:size( B, 1 )
    %         B( r, c ) = A( row( c ), col( r, c ));
    %     end
    % end
    
    % Simple for-loop (further vectorization possible)
    r = 1:size( B, 1 );
    for c = 1:size( B, 2 )
        B( r, c ) = A( row( c ), col( r, c ));
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-07
      • 2017-09-25
      • 2011-01-21
      • 1970-01-01
      • 1970-01-01
      • 2014-10-27
      相关资源
      最近更新 更多