Opposite of Part in matrices?
Do you mean this?
mk = RandomReal[{-1, 1}, {6, 6}];
kept = {1, 2, 4, 5, 6}
KBB = mk[[kept, kept]]
newmk = ConstantArray[0., Dimensions[mk]];
newmk[[kept, kept]] = KBB;
newmk
Henrik's answer gives the most straightforward and convenient way.
An alternative, at the cost of two extra pairs of braces, is to use SparseArray[{{0}}, Dimensions@m]
instead of ConstantArray[0, Dimensions@m]
.
A function that takes two matrices, (m
and k
), and a list of keptrows
and keptcols
as input, and produces a SparseArray
with the dimensions of m
where the values at cells corresponding to the kept rows and columns are set to the values of the matrix k
:
ClearAll[saF]
saF[m_, k_, {keptrows_, keptcols_}] :=
Module[{sa = SparseArray[{{0}}, Dimensions@m]}, sa[[keptrows, keptcols]] = k; sa]
Examples:
SeedRandom[1]
mk = RandomInteger[9, {6, 6}];
keptrows = keptcols = {1, 2, 4, 5, 6};
kbb = mk[[keptrows, keptcols]];
saF[mk, kbb, {keptrows, keptcols}] // Normal // TeXForm
$ \left( \begin{array}{cccccc} 2 & 1 & 0 & 9 & 7 & 5 \\ 7 & 2 & 0 & 3 & 6 & 3 \\ 0 & 0 & 0 & 0 & 0 & 0 \\ 3 & 7 & 0 & 4 & 1 & 4 \\ 9 & 1 & 0 & 7 & 6 & 7 \\ 8 & 1 & 0 & 2 & 8 & 5 \\ \end{array} \right)$
aa = Array[a, {8, 7}];
keptrows = {2, 4, 6, 7};
keptcols = {1, 5, 6};
kaa = aa[[keptrows, keptcols]] /. a -> b;
saF[aa, kaa, {keptrows, keptcols}] // Normal // TeXForm
$ \left( \begin{array}{ccccccc} 0 & 0 & 0 & 0 & 0 & 0 & 0 \\ b(2,1) & 0 & 0 & 0 & b(2,5) & b(2,6) & 0 \\ 0 & 0 & 0 & 0 & 0 & 0 & 0 \\ b(4,1) & 0 & 0 & 0 & b(4,5) & b(4,6) & 0 \\ 0 & 0 & 0 & 0 & 0 & 0 & 0 \\ b(6,1) & 0 & 0 & 0 & b(6,5) & b(6,6) & 0 \\ b(7,1) & 0 & 0 & 0 & b(7,5) & b(7,6) & 0 \\ 0 & 0 & 0 & 0 & 0 & 0 & 0 \\ \end{array} \right)$
This is a version which doesn't require modifying a matrix in place, although it is the same basic idea. I use a background matrix of zeroes, the set replace at positions construct from kept from the corresponding positions in KBB (which depend only on the length of kept):
z = Array[0 &, {6, 6}];
ReplacePart[
z,
MapThread[
#1 -> Extract[KBB, #2] &,
{Tuples[kept, 2], Tuples[Range[Length[kept]], 2]}
]
]