2
$\begingroup$

If I want to add the columns of {1,2} to each of the columns of say

{{1,2},{3,2},{4,2}}

resulting in

{{2, 4}, {4, 4}, {5, 4}}

How would I do this? and for any given number of rows?

{{1,2},{3,2}...{x,y}}

$\endgroup$
1

3 Answers 3

5
$\begingroup$

Every time anyone says "I want to do x to every item in a list" think Map

m={{1,2},{3,2},{4,2}};
Map[#+{1,2}&,m]

which returns

{{2,4},{4,4},{5,4}}

If that # and & stuff is too confusing then you can do the same by writing your own function

m={{1,2},{3,2},{4,2}};
f[v_]:=v+{1,2};
Map[f,m]

which returns

{{2,4},{4,4},{5,4}}
$\endgroup$
4
$\begingroup$

Another way.

pts = {{1, 2}, {3, 2}, {4, 2}};
TranslationTransform[First@pts] /@ pts
pts = {{1, 2}, {3, 2}, {4, 2}};
ConstantArray[{1, 0, 0}, Length@pts] . pts + pts

{{2, 4}, {4, 4}, {5, 4}}

$\endgroup$
2
$\begingroup$

Two (of probably very many) ways:

data//With[{x = #[[1]]},ArrayReduce[x+#&,#,2]]&

(* {{2, 4}, {4, 4}, {5, 4}} *)

or

data//With[{x = #[[1]]},x+#&/@#]&

where

data ={{1,2},{3,2},{4,2}}

Edit

Add a column to all columns (see this answer by Carl Woll)

addColToAll[mat_,col_] := With[{x=col},mat.SparseArray[{{x,x}->2,Band[{1, 1}]->1,
    {x,_}->1},Dimensions[mat][[2]]]]

Add a row to all rows:

addRowToAll[mat_,row_] := With[{x=row},Transpose[mat].SparseArray[{{x,x}->2,Band[{1, 1}]->1,{x,_}->1},Dimensions[mat][[1]]]//Transpose]

Examples

addRowToAll[data,1]
(* {{2, 4}, {4, 4}, {5, 4}} *)

addRowToAll[data,2]
(* {{4, 4}, {6, 4}, {7, 4}} *)

addRowToAll[data,3]
(* {{5, 4}, {7, 4}, {8, 4}}

addColToAll[data,1]

(* {{2, 3}, {6, 5}, {8, 6}} *) 

data

(* {{1, 2}, {3, 2}, {4, 2}}  *)
$\endgroup$

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