title: Join geo-referenced matrices in MATLAB
body: <p>I have two geo-referenced matrices (gridded climate datasets) with different spatial extent and resolution (i.e., spatial coverage of one pixel on the surface of the Earth) that I would like to join. Let's call them <code>referenceMatrix</code> and <code>targetMatrix</code>. The matrices can be loaded into MATLAB as geotiffs or just matrices with corresponding grids of latitudes/longitudes per pixel. </p>
  
  <p>What I want is to fill <code>NaN</code>-pixels in the <code>targetMatrix</code> with the corresponding value from the <code>referenceMatrix</code>. I can do it using a <code>for</code>-loop that looks through the pixels one by one, and fills the <code>NaN</code>s in the <code>targetMatrix</code> with data from the <code>referenceMatrix</code> based on the nearest pixel. The method I am using to localize the nearest pixel in space is described here:<br>
  <a href="https://stackoverflow.com/questions/17411274/how-to-find-the-nearest-points-to-given-coordinates-with-matlab">How to find the nearest points to given coordinates with MATLAB?</a></p>
  
  <p>However I need to do this with thousands of matrices, and the <code>for</code>-loop is too slow. Therefore I would like to use logical indexing, e.g. </p>
  
  <pre><code>targetMatrix(isnan(targetMatrix)) = referenceMatrix(isnan(targetMatrix))
  </code></pre>
  
  <p>with the added ability to match pixels in the matrices based on their latitude and longitude. Can any of you point me in a direction with an example of comparing matrices with different extent based on their georeference? </p>
  
  <p>An example of input data and the wanted output below</p>
  
  <pre><code>targetMatrix = [1,  NaN, 3; 
                  NaN, 5,  6]; 
  referenceMatrix = [10, 20, 30, 40; 
                     50, 60, 70, 80]; 
  referenceLatitude = [13.3, 13.3, 13.3, 13.3; 
                       14.1, 14.1, 14.1, 14.1]; 
  referenceLongitude = [3.2, 4.2, 5.2, 6.2; 
                        3.2, 4.2, 5.2, 6.2];  
  targetLatitude = [13.4, 13.4, 13.4; 
                    13.9, 13.9, 13.9]; 
  targetLongitude = [3.1, 3.6, 4.1; 
                     3.1, 3.6, 4.1]; 
  
  wantedOutput = [ 1, 10, 3; 
                  50,  5, 6];
  </code></pre>
  
  <p>The wanted output consists of the original values from the <code>targetMatrix</code> where the <code>NaN</code>s are filled with the nearest (in space) value from the <code>referenceMatrix</code>, i.e., <code>10</code> and <code>50</code>.</p>