Mathematica帮助〜随机更改矩阵中的元素

时间:2014-03-14 18:17:14

标签: matrix wolfram-mathematica

我有一个10X10矩阵,其元素的值为-1或1.给定百分比,我想随机将元素百分比更改为其相反的值。例如,如果我输入20%我想随机更改20个元素;如果值为-1,我希望它更改为1,如果值为1,我希望它翻转为-1。我希望这是有道理的。谢谢

2 个答案:

答案 0 :(得分:2)

 (example = Table[1, {10}, {10}] ) // MatrixForm

enter image description here

 example RandomChoice[{80, 20} -> {1, -1} , {10, 10}] // MatrixForm

enter image description here

如果您希望完全 20翻转,您可以这样:

 example Partition[RandomSample[Table[-1, {20}]~Join~Table[1, {80}], 100], 10]

答案 1 :(得分:1)

In[1]:= m = 2*RandomInteger[{0, 1}, {10, 10}] - 1

Out[1]= {{1, 1, -1, -1, -1, -1, 1, -1, 1, 1},
 {-1, -1, 1, -1, -1, -1, -1, 1, 1, -1},
 {-1, -1, 1, -1, 1, 1, 1, 1, -1, 1},
 {1, 1, -1, 1, -1, -1, -1, 1, -1, -1},
 {1, -1, 1, 1, 1, -1, 1, -1, 1, 1},
 {-1, 1, 1, -1, -1, -1, -1, 1, 1, 1},
 {-1, -1, 1, 1, 1, 1, -1, 1, -1, 1},
 {-1, -1, -1, 1, -1, -1, -1, -1, -1, 1},
 {1, -1, 1, 1, 1, 1, -1, 1, -1, 1},
 {-1, -1, -1, 1, -1, 1, 1, -1, -1, 1}}

In[2]:= flip[m_, p_] := Module[{vm = m, v},
 v = RandomChoice[Range[100] - 1, p];
 For[i = 1, i <= p, i++,
  vm[[Quotient[v[[i]], 10] + 1, Mod[v[[i]], 10] + 1]] *= -1
 ];
 vm
];
fm = flip[m, 3] (* flip 3% *)

Out[3]= {{1, 1, -1, -1, -1, -1, 1, -1, 1, 1},
 {-1, -1, 1, -1, -1, -1, -1, 1, 1, -1},
 {-1, -1, 1, -1, 1, 1, 1, 1, -1, 1},
 {1, 1, -1, 1, -1, -1, -1, 1, -1, -1},
 {1, -1, 1, 1, 1, -1, 1, -1, 1, 1},
 {-1, 1, 1, -1, -1, -1, -1, 1, 1, 1},
 {-1, -1, 1, 1, -1, 1, -1, 1, -1, 1},
 {-1, -1, -1, 1, -1, 1, -1, -1, -1, 1},
 {1, -1, 1, 1, 1, 1, -1, 1, -1, 1},
 {-1, 1, -1, 1, -1, 1, 1, -1, -1, 1}}

In[4]:= MapThread[#1-#2&, {m, fm}] (*subtract matricies to hilight changes*)

Out[4]= {{0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
 {0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
 {0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
 {0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
 {0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
 {0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
 {0, 0, 0, 0, 2, 0, 0, 0, 0, 0},
 {0, 0, 0, 0, 0, -2, 0, 0, 0, 0},
 {0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
 {0, -2, 0, 0, 0, 0, 0, 0, 0, 0}}

使用*的替代方法,用于成对元素乘法,而不是矢量点积

flip[m_, p_] := Partition[
  Flatten[m]*RandomSample[Join[Table[-1, {p}], Table[1, {100-p}]]], 10];