title: Reshape a 3D array and remove missing values
body: <p>I have an NxMxT array where each element of the array is a grid of Earth. If the grid is over the ocean, then the value is 999. If the grid is over land, it contains an observed value. N is longitude, M is latitude, and T is months.
  In particular, I have an array called <code>tmp60</code> for the ten years 1960 through 1969, so 120 months for each grid. </p>
  
  <p>To test what the global mean in January 1960 was, I write:</p>
  
  <pre><code>tmpJan60=tmp60(:,:,1);
  tmpJan60(tmpJan60(:,:)&gt;200)=NaN;
  nanmean(nanmean(tmpJan60))
  </code></pre>
  
  <p>which gives me 5.855. </p>
  
  <p><strong>I am confused about the reshape function.</strong> I thought the following code should yield the same average, namely 5.855, but it does not:</p>
  
  <pre><code>load tmp60
  
  N1=size(tmp60,1)
  N2=size(tmp60,2)
  N3=size(tmp60,3)
  
  reshtmp60 = reshape(tmp60, N1*N2,N3);
  reshtmp60( reshtmp60(:,1)&gt;200,: )=[];
  mean(reshtmp60(:,1))
  </code></pre>
  
  <p>this gives me -1.6265, which is not correct.</p>
  
  <p>I have checked the result in Excel (!) and 5.855 is correct, so I assume I make a mistake in the reshape function. </p>
  
  <p>Ideally, I want a matrix that takes each grid, going first down the N-dimension,  and make the 720 rows with 120 columns (each column is a month). These first 720 rows will represent one longitude band around Earth for the same latitude. Next, I want to increase the latitude by 1, thus another 720 rows with 120 columns. Ultimately I want to do this for all 360 latitudes. 
  If longitude and latitude were inputs, say column 1 and 2, then the matrix should look like this:</p>
  
  <pre><code>temp = [-179.75 -89.75 -1  2 ...
          -179.25 -89.75 2  4 ...
             ...
           179.75 -89.75 5 9 ...
          -179.75 -89.25 2  5 ...
          -179.25 -89.25 3  4 ... 
            ...
          -179.75  89.75 2  3 ...
            ...
           179.75  89.75 6  9 ...]
  </code></pre>
  
  <p>So <code>temp(:,3)</code> should be all January 1960 observations.</p>
  
  <p>One way to do this is:</p>
  
  <pre><code>grid1 = tmp60(1,1,:);
  g1 = reshape(grid1, [1,120]);
  grid2 = tmp60(2,1,:);
  g2 = reshape(grid2,[1,120]);
  g = [g1;g2];
  </code></pre>
  
  <p>But obviously very cumbersome.</p>
  
  <p>I am not able to automate this procedure for the N*M elements, so comments are appreciated!</p>
  
  <p><a href="https://drive.google.com/drive/folders/0Bw03U0rliS5PUnpIZmVUbUFCc0k?usp=sharing" rel="nofollow noreferrer">A link to the file tmp60.mat</a></p>