【问题标题】:Create all possible Mx1 vectors from an Nx1 vector in MATLAB在 MATLAB 中从 Nx1 向量创建所有可能的 Mx1 向量
【发布时间】:2013-11-20 22:08:53
【问题描述】:

我正在尝试从 MATLAB 中的 1xN 向量(字母)创建所有可能的 1xM 向量(单词)。 N 大于 M。例如,我想从 4x1“字母”alphabet = [1 2 3 4] 创建所有可能的 2x1“单词”;

我希望得到如下结果:

[1 1]
[1 2]
[1 3]
[1 4]
[2 1]
[2 2]
...

我想让 M 成为我日常工作的输入,但我事先并不知道。否则,我可以使用嵌套的 for 循环轻松做到这一点。无论如何要这样做?

【问题讨论】:

标签: arrays algorithm matlab vector


【解决方案1】:

试试

[d1 d2] = ndgrid(alphabet);
[d2(:) d1(:)]

M上参数化:

d = cell(M, 1);
[d{:}] = ndgrid(alphabet);
for i = 1:M
    d{i} = d{i}(:);
end
[d{end:-1:1}]

一般来说,在库中没有 ndgrid 的语言中,参数化 for 循环嵌套的方法是使用递归。

[result] = function cartesian(alphabet, M)
    if M <= 1
        result = alphabet;
    else
        recursed = cartesian(alphabet, M-1)
        N = size(recursed,1);
        result = zeros(M, N * numel(alphabet));
        for i=1:numel(alphabet)
            result(1,1+(i-1)*N:i*N) = alphabet(i);
            result(2:M,1+(i-1)*N:i*N) = recursed;  % in MATLAB, this line can be vectorized with repmat... but in MATLAB you'd use ndgrid anyway
        end
    end
end

【讨论】:

  • 哈哈,很简洁! +1
  • 好吧,我还没有测试过。但它应该工作,也许需要一些调整。
  • 那里,有序和参数化!并且经过测试,虽然是在 Matlab Mobile 上,所以我不能在这里轻松剪切和粘贴。
【解决方案2】:

要从任意alphabet 中获取所有k 字母组合,请使用

n = length(alphabet);
aux = dec2base(0:n^k-1,n)
aux2 = aux-'A';
ind = aux2<0;
aux2(ind) = aux(ind)-'0'
aux2(~ind) = aux2(~ind)+10;
words = alphabet(aux2+1)

alphabet 可以由最多 36 个 元素组成(根据dec2base)。这些元素可能是数字字符

这是如何工作的

当以 n 为底表示时,数字 0、1、...、n^k-1 给出了取自 0、...、n-1 的所有 k 个数字组。 dec2base 转换为基数 n,但以字符串的形式给出结果,因此需要转换为相应的数字(这是 auxaux2 的一部分)。然后我们加 1 使数字 1,...,n。最后,我们用它来索引alphabet,以使用字母表中数字的真实字母。

字母示例

>> alphabet = 'abc';
>> k = 2;

>> words

words =

aa
ab
ac
ba
bb
bc
ca
cb
cc

数字示例

>> alphabet = [1 3 5 7];
>> k = 2;

>> words

words =

     1     1
     1     3
     1     5
     1     7
     3     1
     3     3
     3     5
     3     7
     5     1
     5     3
     5     5
     5     7
     7     1
     7     3
     7     5
     7     7

【讨论】:

  • base 大于10 时,我认为减法-'0' 的技巧不会奏效。
  • 为什么减去'0'会将字符串变成数字? @BenVoigt 不幸的是,我实际上使用的是 > 10 的基数,它不像你说的那样工作。
  • @iab 已更正。不太优雅,但嘿
  • @LuisMendo 我选择了这个作为最佳答案,因为它不涉及 for 循环,并且工作得到了很好的解释。不要贬低其他解决方案,但我发现这个例程最容易理解,并且很容易快速判断代码在做什么。
【解决方案3】:

在 Matlab 中使用 ndgrid 函数

[a,b] = ndgrid(alphabet)

【讨论】:

  • 你有没有偶然看到 Ben Voigt 的回答?
猜你喜欢
  • 2018-06-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-27
  • 1970-01-01
  • 2020-12-16
  • 1970-01-01
相关资源
最近更新 更多