I have a 3x3 matrix
testweightedgraph = {{{}, {p, q, pq, pq}, {}}, {{p, q, pq,
pq}, {q}, {}}, {{}, {}, {}}};
whose elements are (possibly empty) lists.
I would like to apply the pure function
1 - Apply[Times, 1 - #] &
to every nonempty element of the matrix, leaving the empty elements exactly as they are. The result I want is this:
{{{}, {1 - (1 - p) (1 - pq)^2 (1 - q)}, {}}, {{1 - (1 - p) (1 -
pq)^2 (1 - q)}, {q}, {}}, {{}, {}, {}}}
If I use
Map[{1 - Apply[Times, 1 - #]} &, testweightedgraph, {2}]
then I get
{{{0}, {1 - (1 - p) (1 - pq)^2 (1 - q)}, {0}}, {{1 - (1 - p) (1 -
pq)^2 (1 - q)}, {q}, {0}}, {{0}, {0}, {0}}}
which is perfect, except that all instances of {0}
should be replaced by {}
.
Rather than patching the result, by somehow replacing {0}
s by {}
s, I would like to get it right in the first place.
One option seems to be to use Position
and feed its results to MapAt
. This has two disadvantages for me: 1) Perhaps Position
needs to be told exactly what to look for, and cannot be asked to look for elements satisfying a pattern (such as, in this case "not being the empty list"). 2) If we are going to have to use pattern matching anyway, then isn't there a more direct way to do it, without using Position
or MapAt
?
I have studied the tutorials on Pattern Matching but I confess I find it very hard to understand.