When to use find, loops or if?
조회 수: 2 (최근 30일)
이전 댓글 표시
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.
채택된 답변
Matt Tearle
2011년 10월 18일
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.
추가 답변 (3개)
Grzegorz Knor
2011년 9월 28일
Start solve your task by reading this topic:
Then you will need the mean function and some matrix indexing:
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Data Distribution Plots에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!