Re: take square of the second and third column of a table
- To: mathgroup at smc.vnet.net
- Subject: [mg124189] Re: take square of the second and third column of a table
- From: Helen Read <readhpr at gmail.com>
- Date: Thu, 12 Jan 2012 04:19:20 -0500 (EST)
- Delivered-to: l-mathgroup@mail-archive0.wolfram.com
- References: <jel20o$lkl$1@smc.vnet.net>
On 1/11/2012 5:21 PM, hanciong awesome wrote: > Hello, suppose I have a very long table like this: > > 1 2 3 > 4 5 6 > 7 8 9 > ....... > 2 3 4 > > how can I take square of the 2nd and 3rd column? I always do it by > making a new table. so let's say the above table is A and it has 100 > lines, then I make the new table as the following: > > B=Table[{A[[n]][[1]],A[[n]][[2]]^2,A[[n]][[3]]^2},{n,1,100}] > > But if the length of the table is unknown, this way is impractical. > Could anyone suggests better way? thank you > Well, Mathematica knows the length of your table. table = RandomInteger[{-10, 10}, {50, 3}] Table[{table[[n]][[1]], table[[n]][[2]]^2, table[[n]][[3]]^2}, {n, 1, Length[table]}] That said, Map would be a lot easier. Make a little function for what you want to do to one row, and Map it across your table, like so. f[{x_, y_, z_}] := {x, y^2, z^2} Map[f, table] Even quicker, once you get the hang of working with pure functions: Map[{#[[1]], #[[2]]^2, #[[3]]^2} &, table] -- Helen Read University of Vermont