如何在 Matlab 中随机打乱现有矩阵的元素子集?

How do I randomly shuffle a subset of the elements of an existing matrix in Matlab?

我在 Matlab 中有一个值范围为 0 到 3 的矩阵。我想随机打乱矩阵的元素,但仅限于值在 1 -3 范围内的单元格(因此仅限于整个矩阵的子集)。有没有办法做到这一点?谢谢。

您可以通过获取所有感兴趣的值的索引(例如 logical index), randomly permuting their order using randperm,然后使用相同的索引将它们分配回矩阵:

% Sample matrix with values from 0 to 3:
M = randi([0 3], 5)

M =

     3     1     0     3     0
     0     3     3     2     0
     1     0     2     1     0
     1     1     2     2     0
     3     0     0     1     0

index = (M > 0);    % Index of values from 1 to 3
values = M(index);  % Vector of indexed values
M(index) = values(randperm(numel(values)))  % Matrix with shuffled values

M =

     2     3     0     2     0
     0     3     1     1     0
     2     0     3     3     0
     1     1     2     1     0
     3     0     0     1     0

请注意,在打乱后的矩阵中,所有的零仍然位于同一位置。另请注意,您仍然拥有相同数量的 1、2 和 3,因为它们只是被洗牌到不同的位置。