0
$\begingroup$

As part of some data anaylsis, I am using the function Trace to give me the name of an array of data, which I then use to label my plots.

eg. my data array is called r1 so I run:

ToString@((Trace[r1])[[1]])

which simply returns the string "r1".

All fine and dandy.

The problem arises when I try to do this for a list of data arrays, I write:

Trace[#]&/@{r1,r2}

which I expect to give me the list {"r1","r2"}. Instead I get {{},{}}.

What am I doing wrong?

Any help will be much appreciated!

$\endgroup$
  • $\begingroup$ @Öskå At the moment, r1 and r2 are both arrays with dimensions {1200,6}. $\endgroup$ – Mashy Jul 24 '14 at 11:56
  • $\begingroup$ {r1, r2} is evaluated first, so the symbols are replaced by their values before Trace sees them. $\endgroup$ – Simon Woods Jul 24 '14 at 12:07
  • $\begingroup$ In other words try Trace[#][[1]] & /@ {Unevaluated@r1, Unevaluated@r2} $\endgroup$ – Öskå Jul 24 '14 at 12:22
  • $\begingroup$ @Öskå This works, thanks a lot. (I'm not sure the etiquette here for asking follow-up but related questions). Is there a way to prevent r1, r2 from being evaluated where I still pass the list {r1,r2} (as opposed to) {Unevaluated@r1, Unevaluated@r2}? I assumed something like: Trace[#][[1]]&/@(Unevaluated/@{r1,r2}) might work, but it still seems to be evaluating the list {r1,r2} first. $\endgroup$ – Mashy Jul 24 '14 at 12:48
  • $\begingroup$ Related by example: (55531) $\endgroup$ – Mr.Wizard Jul 24 '14 at 13:29
1
$\begingroup$

Mapping Trace[]

Since List evaluates its arguments, the construct

Trace /@ { stuff }

will usually give you empty lists because the stuff has been evaluated before Trace sees it (and Mathematica is smart enough not to re-evaluate expressions which haven't changed). There is no more evaluation to be done, so Trace shows nothing.

Solving the actual problem

Personally I would not use Trace for this purpose. You could instead define a function to extract symbol names using SymbolName:

SetAttributes[name, {Listable, HoldFirst}]; 
name[x_] := SymbolName[Unevaluated @ x]

I've made name Listable so that it automatically threads over lists.

E.g.

r1 = {1, 2, 3};
r2 = {2, 4, 6};

name[r1]
(*  "r1"  *)

name[{r1, r2}]
(*  {"r1", "r2"}  *)
$\endgroup$

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