Why aren't my variables the same dimension?

조회 수: 1 (최근 30일)
Shannon
Shannon 2015년 8월 4일
댓글: Shannon 2015년 8월 7일
Hi All,
I was hoping a new pair of eyes could find what is wrong with the following code:
v = landPercent(x1:x2,y1:y2)>80;
SWNA_S = zeros(length(time),1);
for i = 1:length(time);
nonZero = nonzeros(v.*pr(x1:x2,y1:y2,i));
Area = nonzeros(v.*areacell(x1:x2,y1:y2));
sumArea = sum(Area);
prArea = Area .* nonZero;
sum_prArea = sum(prArea);
SWNA_S(i) = sum_prArea/sumArea;
end
For some reason the nonZero and Area variables are different dimensions at i=425. I tried putting an index for Area: Area = nonzeros(v.*areacell(x1:x2,y1:y2,i)); But then it says that the index exceeds the matrix dimension. I think I'm on the right path with that approach, but wonder if anyone could help me figure out how to put the correct index in that doesn't exceed the matrix dimensions?
Thanks.
  댓글 수: 3
Shannon
Shannon 2015년 8월 4일
Good point. pr is a 192x145x1872 (1872 dimension is time) array of precipitation values and area cell is a 192x145 array of grid cell area values. I'm trying to calculate the values of each variable across an averaging region called SWNA_S. I am then weighting the pr value in each grid cell within SWNA_S according to each grid cell area, which is why I multiply Area * nonZero, which need to be the same size. I'm not sure why they aren't the same size in some time steps, because I am extracting those values from (x1:x2,y1:y2) for both pr and areacell. Thanks!
Walter Roberson
Walter Roberson 2015년 8월 4일
The nonzeros() selects for nonzero values. Your code is assuming that the zeros come only from v, but if that is not true, if there is a 0 in pr, then there would be fewer nonzeros() for that layer than you expect. The code I suggest handles it a different way, by using v as a logical index.

댓글을 달려면 로그인하십시오.

채택된 답변

Walter Roberson
Walter Roberson 2015년 8월 4일
pr(x1:x2,y1:y2,425) contains a 0 in a position where v is true. In the iterations before that, that was not true.
With the extra 0, the nonzeros of the multiplication are different than the nonzero of the areacell.
To repair this:
before the loop calculate
areaxy = areacell(x1:x2,y1:y2);
Area = areaxy(v);
sumArea = sum(Area);
and inside the loop,
pri = pr(x1:x2,y1:y2,i);
nonZero = pri(v);
There is no need to recalculate Area or sumArea inside the loop as you do not change the array and you do not change the indices.
  댓글 수: 1
Shannon
Shannon 2015년 8월 7일
Hi Walter, that worked like a charm. Thanks!!

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by