Question

I have a 10X10 matrix with elements that have the values -1 or 1. Given a percentage, I want to randomly change that percentage of elements to its opposite value. For example, if I input 20% i want to randomly change 20 elements; if the value is -1 I want it to change to 1, and if the value is 1 I want it to flip to -1. I hope that makes sense. Thanks

Was it helpful?

Solution 2

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}}

Alternate method using * for pairwise element multiply, not vector dot product

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

OTHER TIPS

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

enter image description here

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

enter image description here

In case you want exactly 20 flipped you can get that like this:

 example Partition[RandomSample[Table[-1, {20}]~Join~Table[1, {80}], 100], 10]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top