Re: take square of the second and third column of a table

• To: mathgroup at smc.vnet.net
• Subject: [mg124187] Re: take square of the second and third column of a table
• From: Bill Rowe <readnews at sbcglobal.net>
• Date: Thu, 12 Jan 2012 04:18:38 -0500 (EST)
• Delivered-to: l-mathgroup@mail-archive0.wolfram.com

```On 1/11/12 at 5:20 PM, hanciong at gmail.com (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

There are any number of ways to accomplish what you want.

In[14]:= data = Partition[Range[9], 3];

Using pattern matching and a replacement rule:

In[15]:= data /. {a_?NumericQ, b_, c_} -> {a, b^2, c^2}

Out[15]= {{1, 4, 9}, {4, 25, 36}, {7, 64, 81}}

using a pure function and Map:
In[16]:= {#[[1]], #[[2]]^2, #[[3]]^2} & /@ data

Out[16]= {{1, 4, 9}, {4, 25, 36}, {7, 64, 81}}

assigning each column to a variable:

In[17]:= {x, y, z} = Transpose[data]; Transpose[{x, y^2, z^2}]

Out[17]= {{1, 4, 9}, {4, 25, 36}, {7, 64, 81}}

Or using Table without knowing how long the resulting table needs to be:

In[18]:= Table[{data[[1, n]], data[[2, n]]^2, data[[3, n]]^2}, {n,
Length@data}]

Out[18]= {{1, 16, 49}, {2, 25, 64}, {3, 36, 81}}

```

• Prev by Date: Re: take square of the second and third column of a table
• Next by Date: Re: Unit testing using imported data
• Previous by thread: Re: take square of the second and third column of a table
• Next by thread: Re: take square of the second and third column of a table