4
$\begingroup$

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.

$\endgroup$
5
  • 2
    $\begingroup$ Did you search the site before posting? This has been asked a bunch of times... $\endgroup$ Dec 5, 2018 at 12:13
  • $\begingroup$ There is the insert function I believe is useful for you. $\endgroup$
    – user59583
    Dec 5, 2018 at 12:13
  • $\begingroup$ a.DiagonalMatrix[{1, 1, 1, 0, 1}] $\endgroup$
    – user1066
    Dec 5, 2018 at 12:53
  • $\begingroup$ @MariusLadegårdMeyer, yes I did, but previous questions seemed to look for more complex things. Thanks $\endgroup$
    – Patricio
    Dec 5, 2018 at 18:54
  • $\begingroup$ Related (not dupe): mathematica.stackexchange.com/questions/3069/… $\endgroup$
    – Michael E2
    Jun 28, 2022 at 15:53

3 Answers 3

5
$\begingroup$

What about

a[[All, replacepos]] = b

?

$\endgroup$
4
$\begingroup$

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
  ]
$\endgroup$
1
  • 1
    $\begingroup$ It wd be nice to compare with these suggestions to use ReplacePart or SubsetMap. $\endgroup$
    – Alan
    May 2, 2023 at 17:30
1
$\begingroup$
a = RandomReal[9, {5, 5}]
(a[[#, 4]] = 0) & /@ Range@5
a
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.