【问题标题】:How to find all permutations (with repetition) in MATLAB?如何在 MATLAB 中找到所有排列(重复)?
【发布时间】:2013-09-06 15:19:12
【问题描述】:

假设我有 4 个字母,我想将它们排列在 3 个位置(允许重复),那么我将有 43=64 种可能的排列。如何计算和打印它们?

【问题讨论】:

标签: matlab permutation cartesian-product


【解决方案1】:

伪代码解决方案:

Generate the (base ten) numbers 0 to 63.
Change them to base 4, which only has the digits 0, 1, 2, and 3.
Convert numbers to letters.

实际的 Matlab 代码留给学生作为练习。

【讨论】:

    【解决方案2】:

    简化Amro's answer,你可以使用这个:

    %// Sample data
    x = 'ABCD';                 %// Set of possible letters
    K = 3;                      %// Length of each permutation
    
    %// Create all possible permutations (with repetition) of letters stored in x
    C = cell(K, 1);             %// Preallocate a cell array
    [C{:}] = ndgrid(x);         %// Create K grids of values
    y = cellfun(@(x){x(:)}, C); %// Convert grids to column vectors
    y = [y{:}];                 %// Obtain all permutations
    

    Matrix y 应该存储您所追求的排列。

    【讨论】:

      【解决方案3】:

      文件交换中的函数N_PERMUTE_K怎么样?

      【讨论】:

        【解决方案4】:

        直观的单线:

        unique(nchoosek(repmat('ABCD', 1,4), 3), 'rows')
        

        虽然好看,但是速度慢,效率低。不要将它用于大型数据集。

        【讨论】:

        • 不错的尝试。虽然这适用于 Matlab,但 GNU/Octave(4.0.0 版)无法解释它,因为 nchoosek 只能接受数字向量。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-09-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多