Write a block of code that generates a 4x4 matrix with randomized real number entries each between 0 & 1, then selects 3 matrix entries at random, and finally replaces these 3 entries with a "nan" string.
Next, create a function to replace each "nan" in the matrix you just generated with the mean of the numbers that appear in that column. Note that you are safe in assuming that each column contains at least one real number. Throughout this problem, use list manipulations, patterns, and rules, but not loops.
Here is what I did for part (1):
mat = RandomReal[{0, 1}, {4, 4}]
newMat = mat /. {mat[[RandomInteger[{1, 4}]]][[RandomInteger[{1,
4}]]] -> "nan",
mat[[RandomInteger[{1, 4}]]][[RandomInteger[{1, 4}]]] -> "nan",
mat[[RandomInteger[{1, 4}]]][[RandomInteger[{1, 4}]]] -> "nan"}
But the problem with this is that sometimes, we may choose the same matrix entry twice, resulting in a matrix with only 2 or possibly 1 deleted element! This obviously doesn't work then.
I was thinking of flattening the matrix and then somehow picking out three distinct elements in this list and then replacing them with "nan"
. How do I randomly pick three things so that hey are distinct and then replace them with "nan"
? From there I would just repartition the list.
For part (2), I'm really stuck. I know I'll have to transpose the matrix and then take the mean of each list, but the problem with that is: how do I take the mean of a list with an "nan"
string in it? How do I disregard the string in the list? I also don't know how I can do this without flattening the whole matrix out, thus losing the data for each column.
I was thinking about doing using Cases
within Cases
. Is that a good start?
flatMat = Flatten[mat]
thenflatMat /. {RandomSample[flatMat, 3] -> {"nan", "nan", "nan"}}
$\endgroup$list = RandomSample[flatMat, 3];
andPartition[ flatMat /. {x_ /; x === list[[1]] -> "nan", x_ /; x === list[[2]] -> "nan", x_ /; x === list[[3]] -> "nan"}, 4]
solves part 1. Thanks. Now on to part (2)... $\endgroup$