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 Center および File ExchangeWeather and Atmospheric Science についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by