# Divide column of a matrix by a specific number [duplicate]

Imagine there is a matrix as below

de= {{311.026, 1.06259}, {311.033, 1.6268}, {311.054,
1.0648}, {311.051, 1.06541}, {311.059, 1.0667}, {311.092,
1.06786}, {311.143, 1.06894}, {311.193, 1.06995}, {311.234,
1.07147}, {311.333, 1.07193}, {311.445, 1.07341}, {311.408,
1.07418}, {311.62, 1.07813}, {311.708, 1.07748}, {313.5,
1.08496}, {314.326, 1.09059}, {315.637, 1.09552}, {316.831,
1.10034}, {318.217, 1.10477}, {319.731, 1.1092}, {325.399,
1.12402}, {334.126, 1.13943}, {342.683, 1.15173}}


I want to divide the second element of all {} is divided by a number lets say 2 what is the best way to do that? de = de/{1,2}?

Thanks a lot

• {#1, #2/2} & @@@ {{a, b}, {c, d}} gives {{a, b/2}, {c, d/2}}. – corey979 Jan 10 '18 at 19:37
• {#[[1]], #[[2]]/2} & /@ de – David G. Stork Jan 10 '18 at 19:38
• This is not a vector. It is a matrix. Loosely, that's why what you wrote doesn't work. – Szabolcs Jan 10 '18 at 19:39

de[[All, 2]] /= 2;
de


Or if you can't replace the old values

deNew = de;
deNew[[All, 2]] /= 2;
deNew


de.DiagonalMatrix[{1.,0.5}]


If de is a matrix with many columns then

de.DiagonalMatrix[SparseArray[{2} -> 0.5, {Dimensions[de][[2]]}, 1.]]


performs slightly better; surprisingly, even better than

Module[{deNew = de},
deNew[[All, 2]] *= 0.5;
deNew
]


Here a test:

n = 10000;
k = 2000;
de = RandomReal[{-1, 1}, {n, k}];

b = de.DiagonalMatrix[SparseArray[{2} -> 0.5, {Dimensions[de][[2]]}, 1.]]; // RepeatedTiming

c = Module[{deNew = de},
deNew[[All, 2]] *= 0.5;
deNew
]; // RepeatedTiming


{0.072, Null}

{0.098, Null}

Of course, if de may be modified in place then probably nothing will beat

de[[All, 2]] *= 0.5; // RepeatedTiming


{0.00034, Null}

• This is probably faster than the transpose version. – Szabolcs Jan 10 '18 at 19:49

The fastest non-compiled solution may be

Transpose[Transpose[de]/{1, 2}]


I haven't benchmarked.

There are many other ways.

#/{1, 2} & /@ de

{#1, #2/2} & @@@ de

MapAt[#/2 &, de, {All, 2}]