4

I have been working on a triple-nested list, called datasections, of the given form:

{{{44.5, 0.00185}, {45.2, 0.00186}, {45.5, 0.00186},...},
 {{48.6, 0.00186}, {49.2, 0.00209}, {49.9, 0.00109},...},
 ...
}

I want to multiply all the secondary values within the lowest level of the list by a constant value, while retaining the primary values.

For example, if the constant value was 2, then the outcome would be:

{{{44.5, 0.0037}, {45.2, 0.00372}, {45.5, 0.00372},...},
 {{48.6, 0.00372}, {49.2, 0.00418}, {49.9, 0.00218},...},
 ...
}

Currently, I have written a code which accomplishes the wanted task, but this code loses the triple nested list structure, which I need to retain.

{Join[
 Partition[
  Flatten[datasections[[]], 1][[All, 1]], 1],
 Partition[
  Flatten[datasections[[]], 1][[All, 2]]*2, 1], 2 
]}

Is there a simple way to accomplish the task at hand?

ncuccia
  • 63
  • 5

2 Answers2

7

This command may be helpful to you:

MapAt[2 # &,
 {{{44.5, 0.00185}, {45.2, 0.00186}, {45.5, 0.00186}},
  {{48.6, 0.00186}, {49.2, 0.00209}, {49.9, 0.00109}}}, {All, All, 2}]

It produces this output

{{{44.5, 0.0037}, {45.2, 0.00372}, {45.5, 0.00372}}, 
 {{48.6, 0.00372}, {49.2, 0.00418}, {49.9, 0.00218}}}
Gustavo Delfino
  • 8,348
  • 1
  • 28
  • 58
6

If you want to "safe" your original data make a copy.

data = {{{44.5, 0.00185}, {45.2, 0.00186}, {45.5, 0.00186}}, {{48.6, 0.00186}, {49.2, 0.00209}, {49.9, 0.00109}}};

copy = data;

copy[[All, All, 2]] *= 2

copy // MatrixForm

enter image description here

If you want to change data permanently it's just

 data[[All, All, 2]] *= 2

You obtain the same result with ReplaceAll

data /. {a_, b_?NumericQ} :> {a, 2 b}

(ReplaceAll can become slow on large lists)

eldo
  • 67,911
  • 5
  • 60
  • 168
  • Just to be clear, each comma within [[...]] goes one layer deeper into the list?

    If so, that make all my operations significantly easier.

    – ncuccia Jul 31 '17 at 20:23
  • 1
    Exactly, you might read the documentation about Part. – eldo Jul 31 '17 at 20:26
  • Thanks for the help! That documentation really cleared up my confusion about the list structure. – ncuccia Jul 31 '17 at 20:31