How to speed up the following code. I need to optimize it for fastest performance in Matlab 7.0 version

2 次查看(过去 30 天)
code
  • TIR_KK & WV_KK lat_TIR, lon_TIR are 1400x1400 matrices.
  • V1,V2,W1,W2 are scalars
  • lat_BOX(m,n),lon_BOX(m,n) are scalars.m,n have values 1:300
  • the problem here is to convert a 1400x1400 matrix into a 300x300 matrix.
  • the constraint is to apply nanmean to the set using latitude and longitude
  • values which are also 1400x1400 matrices.
cnt = 0; TIR_KK = 0;WV_KK = 0;
for i = V1:V2
for j = W1:W2
if lat_BOX(m,n) >= latTIR(i,j) && latTIR(i,j) > lat_BOX(m+1,n) && lon_BOX(m,n) <= lonTIR(i,j) && lonTIR(i,j)< lon_BOX(m,n+1)
cnt = cnt+1;
TIR_KK(cnt) = TIR_K(i,j);
WV_KK(cnt) = WV_K(i,j);
% fprintf ('\n %f\t%f',latTIR(i,j),lonTIR(i,j))
end
end
end
CNT_check(m,n) = cnt;
TIR_K_box(m,n) = nanmean(TIR_KK);
WV_K_box(m,n) = nanmean(WV_KK);

回答(2 个)

Justin
Justin 2014-5-2
What is lat_BOX and lon_BOX and where are m and n defined? Also, what is the concept of what the conditional statements are applying?
Since the calculation of each value in the output arrays is based on a conditional statement it may be difficult to avoid for loops. You could try to apply the conditional statements to the entire latTIR and lonTIR arrays. Then you could use the results logical values to index you TIR_K and WV_K and take the mean values of those directly.
For example:
x = [1 2 3 4 5 6];
y = [7; 6; 5; 4; 3; 2];
removeIndex = x<3;
y(removeIndex) = [];
value = nanmean(y);
  1 个评论
Santino M
Santino M 2014-5-3
Thanks Justin for the prompt response. I have added the clarifications to the question. The Speed up of code would be done if I can get a matrix output of indices of a larger matrix using "find" command

请先登录,再进行评论。


Jan
Jan 2014-5-3
编辑:Jan 2014-5-3
Pre-allocation is essential, when larger arrays are created. So try:
max_n = (V2-V2+1) * (W2-W1+1);
TIR_KK = zeros(1, max_n);
WV_KK = zeros(1, max_n);
A nex idea is the vectorization mentioned by Justin already:
index = (lat_BOX(m,n) >= latTIR(V1:V2,W1:W2)) & ...
(latTIR(V1:V2,W1:W2) > lat_BOX(m+1,n)) & ...
(lon_BOX(m,n) <= lonTIR(V1:V2,W1:W2)) & ...
(lonTIR(V1:V2,W1:W2) < lon_BOX(m,n+1));
TIR_K_box(m,n) = nanmean(TIR_K(index));
WV_K_box(m,n) = nanmean(WV_K(index));
By the way, this looks nicer also, such that it faster to debug.
Perhaps using temporary arrays is slightly faster:
T1 = latTIR(V1:V2,W1:W2);
T2 = lonTIR(V1:V2,W1:W2);
index = (lat_BOX(m,n) >= T1) & ...
(T1 > lat_BOX(m+1,n)) & ...
(lon_BOX(m,n) <= T2) & ...
(T2 < lon_BOX(m,n+1));
TIR_K_box(m,n) = nanmean(TIR_K(index));
WV_K_box(m,n) = nanmean(WV_K(index));

类别

Help CenterFile Exchange 中查找有关 Resizing and Reshaping Matrices 的更多信息

标签

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by