MATLAB: Writing nanmedian into an array.

2d array3d arraynanmedian

Hello everyone. I use nanmedian to calculate the median values excluding nan of a 3d Array and then store the elements in a 2d Array as follows.
for i=1:size(tempBeforeDelam,1)
for j=1:size(tempBeforeDelam,2)
if all( abs( diff([ squeeze(tempBeforeDelam(i,j,:)); tempBeforeDelam(i,j,1) ]) ) < 1)
beforeDelam(i,j)= nanmedian(tempBeforeDelam(i,j,1:5),3);
%beforeDelam(i,j)= median(tempBeforeDelam(i,j,1:5),3,'omitnan');
the Problem here with nanmedian or median with omitnan flag is that it is not omitting the Nan only while writing into the Array.
For example,consider row 1279069 and column 1 along my 3rd Dimension,
tempBeforeDelam(1279069,1,1) = 13.4567
tempBeforeDelam(1279069,1,1) = NaN
tempBeforeDelam(1279069,1,1) = 13.3564
tempBeforeDelam(1279069,1,1) = 13.4657
tempBeforeDelam(1279069,1,1) = 13.4346
nanmedian of above 5 elements is 0 in my Output Array. i.e even if there is one Nan Output is Zero. But if call the same row in the command window and find the nanmedian i get the right answer. Can someone tell me why I get a Problem while writing it into the Array and how I can solve it??
I have also attached a Picture to Show the Problem I have.

Best Answer

  • I strongly suspect that your problem is with the if condition rather than nanmedian. if there is a NaN in your matrix, then diff is going to return a NaN, which is never smaller than 1. Therefore your condition will not be true, and the body of the if (the assignment to beforeDelam) is never executed.