5

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

kglr
  • 394,356
  • 18
  • 477
  • 896
kmsin
  • 65
  • 1
  • 7

3 Answers3

10

How about this?

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}

Henrik Schumacher
  • 106,770
  • 7
  • 179
  • 309
8
de[[All, 2]] /= 2;
de

Or if you can't replace the old values

deNew = de;
deNew[[All, 2]] /= 2;
deNew
Coolwater
  • 20,257
  • 3
  • 35
  • 64
6

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}] 
Szabolcs
  • 234,956
  • 30
  • 623
  • 1,263