【问题标题】:Construct Matlab matrix from Cartesian product of two vectors从两个向量的笛卡尔积构造 Matlab 矩阵
【发布时间】:2020-07-27 12:32:48
【问题描述】:

考虑两个 Matlab 向量 A=[1 2 3 4 5] B=[6 7 8 9 10];

我希望您建议编写一个大小为 32x5 的 Matlab 矩阵 C,其中每一行都有:

  • 作为第一个元素A(1)B(1)
  • 作为第二个元素A(2)B(2)
  • 作为第三个元素A(3)B(3)
  • 作为第四个元素A(4)B(4)
  • 作为第五个元素A(5)B(5)

C 不应包含相等的行。 32来自2^5,其中5AB的长度。

 C=[1 2 3 4 5; %all elements from A (1 row)
    6 2 3 4 5; %one element from B (5 rows)
    1 7 3 4 5; 
    1 2 8 4 5; 
    1 2 3 9 5; 
    1 2 3 4 10; 
    6 7 3 4 5; %two elements from B (10 rows)
    ... ;
    6 7 8 4 5; %three elements from B (10 rows)
    ... ;
    6 7 8 9 5; %four elements from B (5 rows)] 
    ... ;
    6 7 8 9 10; %all elements from B (1 row)] 

我可以手动写下C,但我想知道是否有更快的方法来构建它。

【问题讨论】:

    标签: arrays matlab matrix


    【解决方案1】:

    与我对your previous question 的回答类似:

    A = [1 2 3 4 5];
    B = [6 7 8 9 10];
    N = numel(A);
    t = dec2bin(0:2^N-1)-'0';
    [~, ind_sort] = sortrows([sum(t,2) -t]);
    t = t(ind_sort, :);
    AB = [A B];
    ind_AB = t*N + (1:N); % or bsxfun(@plus, t*N, 1:N) in old Matlab versions
    result = AB(ind_AB);
    

    【讨论】:

      猜你喜欢
      • 2018-07-04
      • 2015-06-03
      • 1970-01-01
      • 2023-03-29
      • 1970-01-01
      • 2010-11-28
      • 1970-01-01
      • 2012-04-07
      • 2020-11-03
      相关资源
      最近更新 更多