Message Boards Message Boards

Hints on code optimization? Generating DTMF telephone signals.

Hi!

I'm very new to Mathematica and the Wolfram Language. I purchased a hobbyist license of Mathematica, and I'm progressing through An Elementary Introduction to the Wolfram Language. I have some background in programming, a smattering of many different languages. Along the way through the book, I come up with code ideas of my own to try new things and test what I've learned.

I wrote some code to generate DTMF telephone signals, and I'm wondering if there are strategies to optimize the code. Some of the syntax seems verbose:

k = "123A456B789C*0D";
f = Flatten[Table[{a, b}, {a, {697, 770, 852, 941}}, {b, {1209, 1336, 1477, 1633}}], 1]; Manipulate[
 Play[Sin[f[[Position[Characters[k], x][[1]][[1]]]][[1]] 2 Pi t] + 
   Sin[f[[Position[Characters[k], x][[1]][[1]]]][[2]] 2 Pi t], {t, 0, 1}], {x, Characters[k], Setter}]

Hints and tips on how to make the most of Mathematica and the Wolfram Language would be most welcome. Thank you!

Christopher Fox

POSTED BY: Christopher Fox
4 Replies

Wow! Some great ideas here. This is exactly the sort of help I was hoping to receive. Thank you all!

POSTED BY: Christopher Fox

More on the syntax: Part which you use using [[ and ]] can be done easier:

[[1]][[1]]]][[2]]

can be simplified to:

[[1,1,2]] 

which is much easier to read (part 2 of part 1 of part 1).

And your first line, can also be much more simplified:

Flatten[Table[{a, b}, {a, {697, 770, 852, 941}}, {b, {1209, 1336, 1477, 1633}}], 1]
Tuples[{{697, 770, 852, 941}, {1209, 1336, 1477, 1633}}]

Give the same output! But i find the 2nd one much neater: no variables, no flattening, no double loops, and can be easily extended to any dimension!

POSTED BY: Sander Huisman

This example in docs will give you a good idea:

freq = Flatten[Outer[List, {697, 770, 852}, {1209, 1336, 1477}], 1];
Grid[Partition[MapIndexed[
   Button[First[#2],
     EmitSound[Play[Total[Sin[2 Pi # t] & /@ #], {t, 0, .1}]]] &, %], 3], Spacings -> {0, 0}]

enter image description here

POSTED BY: Vitaliy Kaurov

All those extracting parts of expressions is not easy to decipher. Perhaps you can pre-calculate the associations between the characters and the sin coefficients this way:

f = Tuples[{{697, 770, 852, 941}, {1209, 1336, 1477, 1633}}];
k = "123A456B789C*0D";
fromCharToCoeffs = AssociationThread[Characters[k] -> Most@f];
Manipulate[
 Play[Sin[fromCharToCoeffs[x][[1]] 2 Pi t] + 
   Sin[fromCharToCoeffs[x][[2]] 2 Pi t], {t, 0, 1}], {x, 
  Characters[k], Setter}]

I have no idea if this will improve the speed of computation, though. Most of the time is spent on building the sound data for Play.

POSTED BY: Gianluca Gorni
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract