【问题标题】:Shuffling a cell array (Matlab)改组单元阵列(Matlab)
【发布时间】:2014-09-22 13:58:35
【问题描述】:

我目前正在尝试使用以下代码在 matlab 中洗牌 1 x N cell 数组的内容:

shuffledframes = frames{randperm(NumberOfFrames)};
frames=shuffledframes;

%printing cell array contents
for i=1:NumberOfFrames
    frames(i)
end

但是框架内容似乎并没有变...

代码中是否有我看不到的错误?

【问题讨论】:

  • 只是一个旁注,而不是你用来显示所有值的循环,你也可以使用:frames{:}

标签: matlab shuffle


【解决方案1】:

你需要更换

shuffledframes = frames{randperm(NumberOfFrames)};

通过以下任一方式:

  1. 标准,推荐方式:

    shuffledframes = frames(randperm(NumberOfFrames));
    
  2. 使用列表的更复杂的替代方案:

    [frames{:}] = frames{randperm(NumberOfFrames)};
    

为什么?在您的原始代码中,frames{randperm(NumberOfFrames)} 给出了一个comma-separated list 的数字。 Matlab 只取该列表的第一个数字并将其分配给shuffledframes

在上面的方法 1 中,frames(randperm(NumberOfFrames)) 使用索引向量对原始元胞数组进行索引,以生成一个新元胞数组,这就是您想要的。

方法 2 具有相同的预期效果,尽管它不必要地更加复杂。它通过将一个列表与另一个列表匹配来工作。即Matlab分别用列表frames{randperm(NumberOfFrames)}的每个值填充列表frames{:}的每个值。

要更清楚地看到这一点,请观察代码第一行的右侧,并与方法 1 进行比较:

>> frames = {1,2,3,4};
>> NumberOfFrames = 4;
>> frames{randperm(NumberOfFrames)} %// Your code. Gives a list of values.
ans =
     3
ans =
     4
ans =
     2
ans =
     1

>> frames(randperm(NumberOfFrames)) %// Approach 1. Gives cell array.
ans = 
    [3]    [1]    [4]    [2]

【讨论】:

  • 在元胞数组的情况下这仍然有效吗??
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-03-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多