4

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.

Henrik Schumacher
  • 106,770
  • 7
  • 179
  • 309
Patricio
  • 583
  • 2
  • 11

3 Answers3

5

What about

a[[All, replacepos]] = b

?

Ulrich Neumann
  • 53,729
  • 2
  • 23
  • 55
4

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
  ]
Henrik Schumacher
  • 106,770
  • 7
  • 179
  • 309
1
a = RandomReal[9, {5, 5}]
(a[[#, 4]] = 0) & /@ Range@5
a
ZaMoC
  • 6,697
  • 11
  • 31