Use names defined in array as input variables in for loop
조회 수: 16 (최근 30일)
I have simulation results from Simulink. I simulate 1 year at a time. After that, I want to merge all result of the different years into 1 array for each output. I know how to do that. But, I have approximately 50 outputs, and I want to know how to do this in a smart way.
For the example, let say I have 3 outputs from the simulation:
Temperature, Humidity, and Pressure, and let say we simulate 2 years.
For temperature, this gives a timetable of Temperature1 (result of 1st year) and Temperature2 (result of second year). We also have Humidity 1 and 2 and Pressure 1 and 2.
Currently, I merge each result in the following way:
TotalTemperature = [Temperature1; Temperature2];
TotalHumidity = [Humidity1; Humidity2];
TotalPressure = [Pressure1; Pressure2];
However, this way is not feasible to do with 50 outputs, so I want to use a for loop.
I want the input for the loop to be an array of
Array = ['Temperature' 'Humidity' 'Pressure']
Or something like that, and then the output to be the same as in the lines above.
The thing I am struggeling with is how to use the names in Array in the loop. I have to do more transformations in a similar way, but I think if this question is answered I can do it is the same way.
Jan 2022년 12월 15일
이동: Jan 님. 2022년 12월 15일
This is one of the most frequently asked questions. See: https://www.mathworks.com/matlabcentral/answers/304528-tutorial-why-variables-should-not-be-named-dynamically-eval .
The answer is: Don't do this. It is a shot in your knee. Do not hide indices in the names of variables as in "Pressure1", "Pressure2", but create an array directly using real indices.
Applying a complicated method to hide an index in the name demands for even more complicates methods to access these variables later on. So TotalTemperature = [Temperature1; Temperature2]; is a good point to start, but why do you create "Temperature1" at first?
Sara Nadeau 2022년 12월 15일
Aside from the discussion about the input to the loop, I am wondering how you're logging the data from simulation. What format is the data in when it comes out of the simulation? For example, is all the data returned as a Simulink.SimulationOutput object? Are you trying to pull data from a Simulink.SimulationData.Dataset object? Something else?
Both of these objects have several functions that could help with postprocessing data in a loop.