Search code examples
wolfram-mathematica

How to name elements in a matrix in mathematica


I have thousands of vectors that represent waveforms, each of those waveforms is representative of a particular sample. I would like to be able to perform an operation on each of those samples and have the output associated with the name of that sample. I have found some information about keys in Mathematica but I can't get them to work correctly. A very simplified example is below. Suppose I have three vectors with 5 elements in each. I could represent this as a matrix in Mathematica as follows:

InputSamples={{1,3,5,6,8}->"SampleA",{7,9,10,45,20}->"SampleB",{90,43,2,1,0}->"SampleC"};

Now suppose I want to do some calculation on each of the samples.

I might choose:

Map[Total,InputSamples]

Now I would want my output to be:

{{SampleA,23},{SampleB,91},{SampleC,136}}

But instead I get:

{{1+SampleA,3+SampleA,5+SampleA,6+SampleA,8+SampleA},{7+SampleB,9+SampleB,10+SampleB,45+SampleB,20+SampleB},{90+SampleC,43+SampleC,2+SampleC,1+SampleC,0+SampleC}}

How can I get this to give the output shown above that I would like or something similar to it?


Solution

  • You get what you ask for with this

    InputSamples={{1,3,5,6,8}->"SampleA",{7,9,10,45,20}->"SampleB",{90,43,2,1,0}->"SampleC"};
    Map[{#[[2]],Total[#[[1]]]}&,InputSamples]
    

    which instantly returns

    {{SampleA,23},{SampleB,91},{SampleC,136}}
    

    Be careful with that and test this method before depending on it

    It is not the usual "try to write everything as punctuation characters" style, but this

    ruletotal[list_->name_]:={name,Total[list]};
    Map[ruletotal,InputSamples]
    

    accomplishes the same thing and might give you some ideas how to do similar tasks in the future.