1
$\begingroup$

I have the following list of matrices

data= {{{23,3,4,5,20.5},{24,3,1,0,20.5},{25,3,7,8,20.5},{26,6,5,4,20.5}},{{23,4,5,3,20.4},{24,4,3,5,20.4},{26,4,3,2,20.4},{27,4,5,7,20.4},{28,4,3,2,20.4}},{{23,4,5,3,20.3},{24,4,3,5,20.3},{26,4,3,2,20.3},{27,4,5,7,20.3},{28,4,3,2,20.3},{29,0,0,2,20.3}},{{23,4,5,3,20.2},{24,4,3,5,20.2},{26,4,3,2,20.2},{30,4,5,7,20.2},{29,0,0,2,20.2}}}

I want to multiply the 2nd,3rd and 4th element of each row by its 5th element, eg: the first row would be {{{23,61.5,82,102.5,20.5},{24,61.5,20.5,0,20.5} and so on...

I know how to multiply these columns

data[[All,All,{2,3,4}]]*data[[All,All,5]] 

but this generates

{{{61.5, 82., 102.5}, {61.5, 20.5, 0.}, {61.5, 143.5, 164.}, {123., 102.5, 82.}}, {{81.6, 102., 61.2}, {81.6, 61.2, 102.}, {81.6, 61.2, 40.8}, {81.6, 102., 142.8}, {81.6, 61.2, 40.8}}, {{81.2, 101.5, 60.9}, {81.2, 60.9, 101.5}, {81.2, 60.9, 40.6}, {81.2, 101.5, 142.1}, {81.2, 60.9, 40.6}, {0., 0., 40.6}}, {{80.8, 101., 60.6}, {80.8, 60.6, 101.}, {80.8, 60.6, 40.4}, {80.8, 101., 141.4}, {0., 0., 40.4}}}

how do I put this back into data ?

$\endgroup$

2 Answers 2

3
$\begingroup$

You were one character away from the solution:

data[[All, All, {2, 3, 4}]] *= data[[All, All, 5]];

data
{{{23, 61.5, 82., 102.5, 20.5}, {24, 61.5, 20.5, 0., 20.5}, . . .

See documentation for TimesBy and Elegant operations on matrix rows and columns.

$\endgroup$
2
  • 1
    $\begingroup$ the power "="...wow :) $\endgroup$
    – ubpdqn
    May 9, 2015 at 8:35
  • $\begingroup$ Thanks and also thanks for the link :) $\endgroup$
    – HuShu
    May 9, 2015 at 8:36
3
$\begingroup$

A couple of approaches:

f[x_] := {x[[1]], Sequence @@ (x[[-1]] # & /@ x[[2 ;; -2]]), x[[-1]]};
g = {#1, #2 #5, #3 #5, #4 #5, #5} &;
Map[f, data, {2}]
g @@@ # & /@ data
$\endgroup$
2
  • 1
    $\begingroup$ A hybrid of these methods: Map[# {1, #[[5]], #[[5]], #[[5]], 1} &, data, {2}] $\endgroup$
    – Mr.Wizard
    May 9, 2015 at 8:37
  • $\begingroup$ Thank you, that works as well! :) $\endgroup$
    – HuShu
    May 9, 2015 at 8:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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