필터 지우기
필터 지우기

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