When to use find, loops or if?
1 vue (au cours des 30 derniers jours)
Afficher commentaires plus anciens
I have a text file containing three columns of data (time in fractions of a day, depth, temp). I need code that will read through the data file and get an average temperature value for every 5 meter depth block in every half hour time block. Then place that result into a matrix (depth:time). I don't know what to use/how to structure it.
2 commentaires
Réponse acceptée
Matt Tearle
le 18 Oct 2011
Two things I notice in your code:
- you're not using j to index into rh and ch -- is that intentional?
- find is returning linear indices from an n-by-2 matrix. This is probably what's causing the error. Your logical condition is testing an n-by-2 matrix, so find will return the non-zero locations as linear indices (ie between 1 and 2n), but you're using those indices (x) as a row index in the next line.
Can you show a few lines of data and what you'd like the result to be? There may well be a cleaner way to do this.
EDIT TO ADD: OK, based on what you've shown, this should do the job:
ch = 0:0.02083:0.70822;
rh = 0:5:420;
m = length(rh)-1;
n = length(ch)-1;
datfin = zeros(m, n);
for j = 1:n;
idx = (cmdata(:,1) >= ch(j)) & (cmdata(:,1) < ch(j+1));
x = cmdata(idx,:);
for i = 1:m;
idx = (x(:,2) >= rh(i)) & (x(:,2) < rh(i+1));
datfin(i, j) = mean(x(idx,3));
end
end
A couple of things, though... Here's the first bit of output I get:
6.2000 NaN
7.4000 2.4500
4.2500 NaN
6.2333 8.5000
6.1000 2.9500
NaN 6.2500
NaN 3.4000
8.5000 3.9833
The second column is what you calculated by hand, but the first column is off. The (1,1) element should be the mean of the values in the third column where the first column is in the range [0,0.0283) and the second is in the range [0,5), right? The only entry I can see that fits that is the third row (0.002070473 1.6 6.2), so the mean of 6.2 looks right -- I don't understand how you got 5.4. Can you clarify?
Also, is your data ordered by the first column? If so, you might be able to speed up the algorithm by avoiding doing the full logical comparisons for every j. If it's not too slow as is, though, I wouldn't bother.
Plus de réponses (3)
Grzegorz Knor
le 28 Sep 2011
Start solve your task by reading this topic:
Then you will need the mean function and some matrix indexing:
0 commentaires
Voir également
Catégories
En savoir plus sur Logical dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!