1
$\begingroup$

I have a large list of $(x,y)$ pairs, and I want to find the index of a particular pair in order to extract some data from another array.

By way of an example,

samplelist = Flatten[Table[{i, j}, {i, 1, 5}, {j, 1, 5}], 1];
(* {{1, 1}, {1, 2}, {1, 3}, {1, 4}, {1, 5}, {2, 1}, {2, 2}, {2, 3}, {2, 
  4}, {2, 5}, {3, 1}, {3, 2}, {3, 3}, {3, 4}, {3, 5}, {4, 1}, {4, 
  2}, {4, 3}, {4, 4}, {4, 5}, {5, 1}, {5, 2}, {5, 3}, {5, 4}, {5, 5}} *)

position = Last@Last@Position[(Boole[# == {1, 3}] & /@ samplelist), n_ /; n == 1];
(* 3 *)

samplelist[[position]]
(* {1, 3} *)

Which is great. But I want to compile this, as the rest of my code is also compiled.

Just doing the following, with SetSystemOptions["CompileOptions" -> "CompileReportExternal" -> True], returns an error because n_ /; n == 1 cannot be compiled.

Note that without the above system options set, it returns no error message, but clearly hasn't compiled, as doing a CompilePrint on the function shows it hasn't.

myPos = Compile[{{list, _Real, 2}, {val, _Real, 1}},
   Position[(Boole[# == val] & /@ list), n_ /; n == 1]];

Is there a way to overcome this and create a compiled function that does what I want?

$\endgroup$
3
$\begingroup$

Use this:

f = Compile[{{lst, _Real, 2}, {val, _Real, 1}}, First@First@Position[lst, val]];
f[samplelist, {1, 3}]
(*3*)
$\endgroup$
  • $\begingroup$ Well there we go, knew I was missing something, thanks! $\endgroup$ – dr.blochwave Nov 25 '14 at 10:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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