Help with nested for and if loops
1 次查看(过去 30 天)
显示 更早的评论
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 个评论
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
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 个评论
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 Center 和 File Exchange 中查找有关 Weather and Atmospheric Science 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!