【问题标题】:How to swap two row vectors inside a row vector?如何在行向量中交换两个行向量?
【发布时间】:2016-09-19 09:04:12
【问题描述】:

我正在尝试交换行向量内的 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 ...... .....

【问题讨论】:

  • 请查看URL这将有助于提升您的内容质量
  • 我不知道你在问什么

标签: arrays matlab random swap


【解决方案1】:

正确且安全的方法是将变量分配给cell,排列单元格的元素,最后连接结果。

想象一个特定的排列,比如[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

您可能唯一需要的就是生成一个随机配置。这很简单:您只需选择 2 个随机索引并将它们交换为 [1, 2, 3, 4]。一个懒惰的选择:

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

【讨论】:

  • 我完全同意。我的印象是,这不是 OP 所要求的,但在提供的信息相当有限的情况下,这是最好的猜测。无论如何+1。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多