2
$\begingroup$

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?

$\endgroup$
0

1 Answer 1

3
$\begingroup$

I'm going to do my best to interpret your question and provide a useful answer. I'm having to guess regarding MapIndexed as your 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.

$\endgroup$
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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