how to put an if statement within for loop

조회 수: 2 (최근 30일)
Roisin Loughnane
Roisin Loughnane 2017년 10월 4일
댓글: Jan 2017년 10월 4일
I compile climate data over many years by month within a for loop, and concatenate these to create a 3D array (of say January's over many years), and I want to take the element-wise mean to get the average over those years:
monthlydata = cell(1, numel(years)); %to hold the monthly data of each year. Preallocated.
years = 2003:2014;
for month = 1:12
for y = 1:numel(years)
monthlydata{y} = load(sprintf('sst_%d_%d.asc', years(y), month));
end
monthlydatac = cat(3, monthlydata{:}); %concatenate all cells along 3rd dimension
monthlymean = mean(monthlydatac, 3); %get mean along 3 dimensions
dlmwrite(sprintf('msst_%d.csv', month), monthlymean); %save
end
The problem is there is missing data for some months taking the form of numbers 250, 251, 252, 253, 254, 255. In some years observations occur in elements of the 3D array but in other years data is missing ( coded as 250:255) for that element. If this is the case I want to take the element-wise mean excluding these 'missing data' values. Would an 'if' statement work? Could anyone advise me on how to do this?
I am new to Matlab and programming and would be very greatly for your help.
  댓글 수: 4
Jan
Jan 2017년 10월 4일
No, this does not help. What is "coded as one of those numbers 250:255"? How could we suggest an explicit solution based on the detail, that "some" elements of "some" years "may" have a value, that you "would like" to keep?
An exact, unequivocal, clear and unique definition is required, to implement this. We cannot do this for you. I assume the actual implementation will be very easy then.
Roisin Loughnane
Roisin Loughnane 2017년 10월 4일
편집: Roisin Loughnane 2017년 10월 4일
NaN = a number between 250 and 255 in my dataset.
For some arrays in the 3D array there are NaN values in some elements, although in corresponding elements in different arrays there is data I am interested in.
The mean is being calculated including a missing data value (here a number between 250 and 255) which I do not want.
I want to exclude any value between 250:255 before getting the mean of the rest of the corresponding elements of the 3D array.

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

채택된 답변

Rik
Rik 2017년 10월 4일
Time for a pure guess: you want to ignore values in the 250-255 range and calculate the mean over the remaining data?
monthlydatac(monthlydatac>=250 & monthlydatac<=255)=NaN;
monthlymean = mean(monthlydatac, 3, 'omitnan');
  댓글 수: 2
Roisin Loughnane
Roisin Loughnane 2017년 10월 4일
Thank you very much.
Sorry for the confusion.
Jan
Jan 2017년 10월 4일
@Rik: +1, a good guess.

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Multidimensional Arrays에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by