I want to replace a column of a matrix. The best I've been able to come up with is
a=RandomReal[9,{5,5}]
b=ConstantArray[0,5]
replacepos=4
Transpose[ReplacePart[Transpose[a], replacepos -> b]],
which does the trick, but looks awkward to me.
I want to replace a column of a matrix. The best I've been able to come up with is
a=RandomReal[9,{5,5}]
b=ConstantArray[0,5]
replacepos=4
Transpose[ReplacePart[Transpose[a], replacepos -> b]],
which does the trick, but looks awkward to me.
Indeed, Transpose has to perform superfluous reorderings which are memory bound. This does the trick and should be fairly efficient:
c = Module[{buffer = a},
buffer[[All, replacepos]] = b;
buffer
]
ReplacePart or SubsetMap.
– Alan
May 02 '23 at 17:30
a.DiagonalMatrix[{1, 1, 1, 0, 1}]– user1066 Dec 05 '18 at 12:53