Help with nested for and if loops

1 次查看(过去 30 天)
Kate
Kate 2013-10-14
评论: Vivek Selvam 2013-10-15
I'm attempting to loop through my 140+ years of climate data to sift out wet and dry seasons in the tropics. I've written some code (below), but 'dry_clim' values aren't being printed. Does anyone see what I've missed here?
Thanks!
function dissect_seasons
%Break met driver into seasonal steps
%Load dataset
climatology=TropicalRainforest_evap;
%Set indices
Jan=(1:12:length(TropicalRainforest_evap));
Jan=Jan';
Feb=(2:12:length(TropicalRainforest_evap));
Feb=Feb';
Mar=(3:12:length(TropicalRainforest_evap));
Mar=Mar';
Apr=(4:12:length(TropicalRainforest_evap));
Apr=Apr';
May=(5:12:length(TropicalRainforest_evap));
May=May';
Jun=(6:12:length(TropicalRainforest_evap));
Jun=Jun';
Jul=(7:12:length(TropicalRainforest_evap));
Jul=Jul';
Aug=(8:12:length(TropicalRainforest_evap));
Aug=Aug';
Sep=(9:12:length(TropicalRainforest_evap));
Sep=Sep';
Oct=(10:12:length(TropicalRainforest_evap));
Oct=Oct';
Nov=(11:12:length(TropicalRainforest_evap));
Nov=Nov';
Dec=(12:12:length(TropicalRainforest_evap));
Dec=Dec';
%Manually set seasons for now, based on Koppen class rules & 100+ yr
%reanalysis climatologies
dryS=vertcat(Jun, Jul, Aug);
wetS=vertcat(Jan, Feb, Mar, Apr, May, Sep, Oct, Nov, Dec);
n=0
dry_clim=zeros(size(climatology));
for j=1:length(TropicalRainforest_evap)
for k=1:length(dryS)
if climatology(:,:,j)==dryS(k)
n=n+1;
dry_clim(:, :, n)=climatology(:,:,j);
end
end
end
  5 个评论
Kate
Kate 2013-10-14
I think that the issue is that I want to pull where climatology(:,:,k)=anything in dryS, does that make sense?
Vivek Selvam
Vivek Selvam 2013-10-14
climatology(:,:,j) would result in a 2 dimensional matrix and dryS(k) a scalar. That is why the comparison is always false and n=0 at the end. Correct me if I am wrong - you want to see if the scalar, dryS(k), matches with any element of climatology(:,:,j)?

请先登录,再进行评论。

回答(1 个)

Vivek Selvam
Vivek Selvam 2013-10-14
Changing the following line from
if climatology(:,:,j)==dryS(k)
to
if nnz(climatology(:,:,j)==dryS(k)) > 0
should make it work.
  2 个评论
Kate
Kate 2013-10-14
Unfortunately Matlab still doesn't find values and write them to the new matrix
Vivek Selvam
Vivek Selvam 2013-10-15
Hi Kate,
I think I understand what you need. I have modified your code.
%Manually set seasons for now, based on Koppen class rules & 100+ yr
%reanalysis climatologies
dryS = vertcat(Jun, Jul, Aug);
wetS = vertcat(Jan, Feb, Mar, Apr, May, Sep, Oct, Nov, Dec);
%%data extraction
dry_clim = climatology(:,:,dryS);
n = length(dry_clim)
Hope this helped!

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Weather and Atmospheric Science 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by