Let's say I have an array
a={{1,2,3},
{4,5,6},
{7,8,9}}
I want to have all elements along the diagonal multiplied by 2.
{{2,2,3},
{4,10,6},
{7,8,18}}
What is the best way to do this? I tried
ReplacePart[a,{i_,i_} -> 2 a[[i,i]]]
and
a[[i_, i_]] = 2 a[[i, i]]
Which both gives the error
Part::pkspec1: The expression i cannot be used as a part specification
I suppose I can do
a*SparseArray[{i_,i_} -> 2,{3,3},1]
but I feel like there should be a simpler way to do this.
RuleDelayed
instead ofRule
:ReplacePart[a, {i_, i_} :> 2 a[[i, i]]]
$\endgroup$Part
as(a[[#, #]] = 2 a[[#, #]]) & /@ Range[3]; a
orTable[a[[i, i]] == 2 a[[i, i]], {i, 1, 3}]; a
$\endgroup$