如何在行向量内交换两个行向量?

时间:2016-05-22 13:10:28

标签: arrays matlab random swap

我正在尝试交换行向量内的2个行向量。

例如:

a=[1 2 3];
b=[5 3];
c=[9 3 7 6];
d=[7 5];

X1= [ a, b , d, c ];

我想进行随机交换,使得a,b,c,d中的两个保持在X1中的相同位置,其余两个在X1中进行随机播放。例如,一些可能的随机互换是: [b,a,d,c] % a and b swap with each other whereas d and c remain at the same place

[d,b,a,c] % a and d swap with each other whereas b and c remain at the same place

[c,b,d,a] % a and c swap with each other whereas b and d remain at the same place ..... .....

1 个答案:

答案 0 :(得分:4)

您正在尝试做的正确而安全的方法是将变量分配给[c, b, a, d],置换单元格的元素,最后连接结果。

想象一下特定的排列,比如[3, 2, 1, 4]。根据映射,该排列可以被编码为% generate input a = [1, 2, 3]; b = [5, 3]; c = [9, 3, 7, 6]; d = [7, 5]; % generate cell to permute tmpcell = {a, b, c, d}; % define our permutation permnow = [3, 2, 1, 4]; % permute and concatenate the result into an array result = [tmpcell{permnow}]; % check if this is indeed OK: disp(isequal(result,[c, b, a, d])) % should print 1 。然后生成数组的相应代码是:

[1, 2, 3, 4]

您可能仍然需要的唯一事情是生成随机配置。这很简单:您只需选择2个随机索引并在nvars = length(tmpcell); % generalizes to multiple variables this way idperm = 1:nvars; i1 = randi(nvars,1); partperm = setdiff(idperm, i1); % vector of remaining indices, avoid duplication i2 = partperm(randi(nvars-1,1)); % second index, guaranteed distinct from i1 permnow = idperm; permnow([i1, i2]) = [i2, i1]; % swap the two indices 中交换它们。一个懒惰的选项:

disp('The probability that your seat will be available is 1/2');