4
$\begingroup$

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?

$\endgroup$
6
$\begingroup$

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)

$\endgroup$
  • $\begingroup$ Just to be clear, each comma within [[...]] goes one layer deeper into the list? If so, that make all my operations significantly easier. $\endgroup$ – ncuccia Jul 31 '17 at 20:23
  • 1
    $\begingroup$ Exactly, you might read the documentation about Part. $\endgroup$ – eldo Jul 31 '17 at 20:26
  • $\begingroup$ Thanks for the help! That documentation really cleared up my confusion about the list structure. $\endgroup$ – ncuccia Jul 31 '17 at 20:31
7
$\begingroup$

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}}}
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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