Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

I have groups of descriptive variable names and dont want to write explicit code for each group, e.g. (and this is a contrived simplification)

EnergySensorALow[1]=somefuncALow[#]& /@ lstSensorA;
EnergySensorAHigh[1]=somefuncAHigh[#]& /@ lstSensorA;
EnergySensorBLow[1]=somefuncALow[#]& /@ lstSensorB;
EnergySensorBHigh[1]=somefuncAHigh[#]& /@ lstSensorB;

etc.

I want create a function that should work as follows:

fnew[sensorType_String]:= 
                           "EnergySensor"+sensorType+"Low[1]"="somefunc"+sensorType+"Low"[#]& /@
                           "lstSensor"+sensorType;

So the function will take an input String, e.g. "A" and then refer to an existing variable name EnergySensorALow[1], which it will set equal to an existing function somefuncALow[#]& and map this over an existing list lstSensorA

The code will also be run periodically when the sensor values update, and each time the function needs to be applied to the list and stored in the appropriate "EnergySensor" variable name. The variable index[n] makes it easy to use the data in a Manipulate and select which dataset needs to be plotted, I prefer not to add additional indexes to accomplish the functionality I need.

Any suggestions?

share|improve this question

1 Answer 1

up vote 3 down vote accepted

I'm going to do my best to interpret your question and provide a useful answer. I'm having to guess regarding MapIndexed as you function doesn't make sense to me.

Starting with this data:

Do[somefuncBOBLow[i] = Prime@i, {i, 10}];

lstSensorBOB = {6, 2, 8, 3, 1};

You could use this:

fnew[sensorType_String] :=
 With[{
    lhs  = Symbol @@ {"EnergySensor" <> sensorType <> "Low"},
    rhs  = Symbol @@ {"somefunc" <> sensorType <> "Low"},
    list = Symbol @@ {"lstSensor" <> sensorType}
   },
   MapIndexed[(lhs[#2[[1]]] = rhs[#]) &, list];
 ]

fnew["BOB"]

To produce these definitions:

Definition[EnergySensorBOBLow]
EnergySensorBOBLow[1]=13

EnergySensorBOBLow[2]=3

EnergySensorBOBLow[3]=19

EnergySensorBOBLow[4]=5

EnergySensorBOBLow[5]=2

Similarly to what I previously suggested I believe you should use another method to structure your data. You can use SubValues definitions in this form:

EnergySensorLow["BOB"][1] = 13;

This way it is easy to address a particular data group via a String key.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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