4
$\begingroup$

q has the coordinates of quadrilateral. I can get the output below with brute-force but I want to find a simpler solution, perhaps something like f<-q[[1;;2]].

Initializations

f[x_, y_] = {{1, 2}, {3, 4}}.{x, y} + {5, 6};
q = {{1, 1}, {3, 1}, {3, 2}, {1, 2}}

Want: better way for this, perhaps in some matrix form?

f[1, 1]
f[3, 1]
f[3, 2]
f[1, 2]
$\endgroup$

2 Answers 2

7
$\begingroup$
f[{x_, y_}] := {{1, 2}, {3, 4}}.{x, y} + {5, 6};
q = {{1, 1}, {3, 1}, {3, 2}, {1, 2}}
f /@ q
(*
 {{8, 13}, {10, 19}, {12, 23}, {10, 17}}
*)

Edit To understand the differences between Map and Apply, try the following (after running the code above):

ClearAll[g];
g @@@ q
(* {g[1, 1], g[3, 1], g[3, 2], g[1, 2]} *)

g /@ q
(* {g[{1, 1}], g[{3, 1}], g[{3, 2}], g[{1, 2}]} *)

Edit

BTW, you could also try:

g @ q
(* g[{{1, 1}, {3, 1}, {3, 2}, {1, 2}}] *)

g @@ q
(* g[{1, 1}, {3, 1}, {3, 2}, {1, 2}] *)

Note that each one of @ , @@ and @@@ makes the function to be applied one level deeper on q.

$\endgroup$
2
  • $\begingroup$ Is this also a Apply -shorthand? $\endgroup$
    – hhh
    Commented Aug 13, 2012 at 17:41
  • 2
    $\begingroup$ @hhh No, it's Map. Just put your cursor on the characters /@ and press F1 (on Windows). Please note that Verde modified your function f subtly to make this work. $\endgroup$ Commented Aug 13, 2012 at 17:50
5
$\begingroup$

I'd define f with SetDelayed (i.e. :=) rather than with Set (i.e. =), (see e.g. this tutorial Immediate and Delayed Definitions) :

f[x_, y_] := {{1, 2}, {3, 4}}.{x, y} + {5, 6}

Apply

Nevertheless if you modify your function f or if you don't, you will need Apply on the first level i.e Apply[f, q, {1}] or its shorthand :

f @@@ q
{{8, 13}, {10, 19}, {12, 23}, {10, 17}}

"...perhaps in some matrix form..." - points collected in q represent a matrix, i.e.

MatrixQ @ q
True

and Apply (@@@) is especially useful for matrices.

Edit

More verbose ways which could be helpful in more general cases than coordinates of quadrilaterals :

ReplaceAll

ReplaceAll (i.e. /.) :

q /. {a_, b_} -> f[a, b]

and for a more complete answer some other ways :

Thread

Thread[ f[ q[[All, 1]], q[[All, 2]] ] ]

MapThread

MapThread[ f, Transpose @ q ]

Inner

Inner[ f, q[[All, 1]], q[[All, 2]], List]
$\endgroup$
0

Your Answer

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

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