【问题标题】:Random permutation of each cell in a cell array元胞数组中每个元胞的随机排列
【发布时间】:2015-10-15 03:18:20
【问题描述】:

我有一个 1-by-4 元胞数组,D。每个单元格元素都包含 2-by-2 双矩阵。我想独立地对每个矩阵进行随机排列,结果我将拥有与D 相同大小的单元数组,但其矩阵的元素将被排列,然后反转,以便再次获得原始的D

对于单个矩阵的情况,我有代码,它的工作原理如下:

A=rand(3,3)
p=randperm(numel(A));
A(:)=A(p)
[p1,ind]=sort(p);
A(:)=A(ind)

但它不适用于元胞数组。

【问题讨论】:

  • 你有没有尝试过?看看使用cellfunfor-loop、randpermsort 的第二个输出。发布您尝试的代码并准确描述您卡在哪里
  • 对于单个任意矩阵,我有代码,它运行良好,但不适用于元胞数组。
  • @Dan %permutation A=rand(3,3) p=randperm(numel(A)); A(:)=A(p) [p1,ind]=排序(p); A(:)=A(ind)
  • @HaybertMarkarian,编辑您的问题以提供更多信息。
  • @HaybertMarkarian 请编辑您的问题并将代码添加到问题中,在 cmets 中不容易阅读。而且,如果它适用于单个矩阵,那为什么不写一个循环呢?

标签: matlab random permutation cell-array


【解决方案1】:

对您来说最简单的解决方案是使用循环:

nd = numel(D);
D_permuted{1,nd} = [];
D_ind{1,nd} = [];
for d = 1:nd)
    A=D{d};
    p=randperm(numel(A));
    A(:)=A(p)
    [~,ind]=sort(p);

    D_permuted{d} = A;
    D_ind{d} = ind;
end

假设您的 D 矩阵只是大小相同(例如 2-by-2)矩阵的列表,那么您可以通过使用 3D 来避免循环双矩阵而不是元胞数组。

例如,如果您拥有这样的D

n = 5;
D = repmat([1,3;2,4],1,1,n)*10  %// Example data

然后你可以像这样进行排列

m = 2*2;  %// Here m is the product of the dimensions of each matrix you want to shuffle
[~,I] = sort(rand(m,n));  %// This is just a trick to get the equivalent of a vectorized form of randperm as unfortunately randperm only accepts scalars
idx = reshape(I,2,2,n);
D_shuffled = D(idx);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-17
    • 1970-01-01
    • 2013-10-27
    相关资源
    最近更新 更多