How to iteratively go through a structure?
10 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Michael Nye
le 2 Août 2024 à 14:54
Modifié(e) : dpb
le 2 Août 2024 à 16:47
I have some data from 100 different tests that I ran. There are 2 variables that were swept through for 10 values each, resulting in 100 tests (i.e. variable 1 is A with 10 elements, variable 2 is B with 10 elements, my test data is from all the permutations of A and B). A few timeseries measurements are made for each test. I have my data saved in a structure like:
Data.A1.B1.meas1
Data.A1.B1.meas2
%...
Data.A1.B1.measN
Data.A1.B2.meas1
Data.A1.B2.meas2
%...
Data.A2.B1.meas1
%...
Data.A10.B10.measN
I need to take the mean of the timeseries data for each test. Is there some way to set up a loop such that I can easily iterate through the struct to do this? Some thing like:
for i = 1:10
for j = 1:10
DataMean = mean(Data.A(i).B(j).meas1)
end
end
Is there a more efficient way to structure the data to make this easier?
0 commentaires
Réponse acceptée
Image Analyst
le 2 Août 2024 à 15:06
Perhaps there is a way to vectorize it. But the for loop is not bad, except that you should use (i,j) indexes on DataMean otherwise you're just overwriting the same variable all the time.
If you have any more questions, then attach your data and code to read it in with the paperclip icon after you read this:
We need to know if you have an array for A that you can index, or if you have 10 separate fields called A1, A2, A3, ... A10. You've implied it both ways but it can only be one way.
2 commentaires
dpb
le 2 Août 2024 à 15:21
Modifié(e) : dpb
le 2 Août 2024 à 16:47
"We need to know if you have an array for A that you can index, or if you have 10 separate fields called A1, A2, A3, ..."
Unfortunately, undoubtedly as is so often the case when starting down this path, @Michael Nye is hoping there is some magic incantation that will turn his loop expression
DataMean = mean(Data.A(i).B(j).meas1)
that refers to the arrays of a struct field into fieldnames referring to Data.Ai.Bj on each iteration. That is the way that leads to buggy, slow, obfuscated code through the ugly eval route.
What he was really looking for is to have built a struct array such that
for i=1:numel(Data)
DataMean(i)=mean(Data(i).A.B.meas1)
end
Unfortunately, unless he has the data saved in some other format so that he can modify the code that created the present, he's left with having to go the route of much pain.
At least, one can <build dynamic fields names> and go at it that way...using strings that will automagically do the num2str() conversion building "A"+i, etc., ...
Plus de réponses (0)
Voir également
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!