0

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!

Artes
  • 57,212
  • 12
  • 157
  • 245
Mashy
  • 85
  • 1
  • 5
  • @Öskå At the moment, r1 and r2 are both arrays with dimensions {1200,6}. – Mashy Jul 24 '14 at 11:56
  • {r1, r2} is evaluated first, so the symbols are replaced by their values before Trace sees them. – Simon Woods Jul 24 '14 at 12:07
  • In other words try Trace[#][[1]] & /@ {Unevaluated@r1, Unevaluated@r2} – Öskå Jul 24 '14 at 12:22
  • @Ö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.

    – Mashy Jul 24 '14 at 12:48
  • Related by example: (55531) – Mr.Wizard Jul 24 '14 at 13:29
  • @Mr.Wizard that's brilliant, thanks. I wish I'd found that example earlier. :) – Mashy Jul 24 '14 at 13:45

1 Answers1

1

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"}  *)
Mr.Wizard
  • 271,378
  • 34
  • 587
  • 1,371
Simon Woods
  • 84,945
  • 8
  • 175
  • 324