title: MATLAB function matrix parameter
body: <p>I've seen a <a href="http://blog.its.ac.id/bsant/knn/" rel="nofollow">blog post</a> about computing the K-nearest neighbor as follows:</p>
  
  <pre><code>function test_targets = knn(train_patterns, train_targets, test_patterns, K)
      % Hubungi budi santosa di budi_s@ie.its.ac.id
      % untuk laporan kesalahan (bug).
      % Implementasi the Nearest neighbor algorithm
      % Inputs:
      %  train_patterns  - Train patterns (obs x dim) D x N
      %  train_targets   - Train targets              1 x N (classes)
      %  test_patterns   - Test  patterns             D x M (M testing)  
      %  K               - jumlah nearest neighbors
      %
      % Outputs
      % test_targets - Predicted targets
  
      L   = length(train_targets);
      Uc          = unique(train_targets);
  
      if (L &lt; K),
         error(’tetangga lebih banyak dari jumlah titik training’)
      end
  
      N               = size(test_patterns, 1);
      test_targets    = zeros(N,1);
      for i = 1:N,
          jar=(train_patterns - repmat(test_patterns(i,:),L,1)).^2;
          dist            = sum(jar,2);%jarak tiap titik data test terhadap data training
          [m, indices]    = sort(dist);%urutkan jarak dr yg terkecil
          yt=train_targets(indices(1:K));%ambil K jarak terkecil dan periksa labelnya
           n               = hist(yt, Uc);%menempatkan data testing ke kelas mana (tergantung Uc)
  
          [m, best]       = max(n);%mencari frekuensi maksimum kelas mana paling banyak dari K tetangga terdekat
  
          test_targets(i) = Uc(best);
      end
  </code></pre>
  
  <p>My problem is that I keep getting the following MATLAB message:</p>
  
  <pre><code>??? Error using ==&gt; minus
  Matrix dimensions must agree.
  </code></pre>
  
  <p>I have 2 matrices:</p>
  
  <pre><code>A is NxD A = 
  670.00 1630.00 2380.00 1
  721.00 1680.00 2400.00 1
  750.00 1710.00 2440.00 1
  660.00 1800.00 2150.00 1
  660.00 1800.00 2150.00 1
  680.00 1958.00 2542.00 1
  440.00 1120.00 2210.00 2
  400.00 1070.00 2280.00 2
  
  B is MxD B =
  750.00 1710.00 2440.00 1
  680.00 1910.00 2440.00 1
  500.00 1000.00 2325.00 2
  500.00 1000.00 2325.00 2
  </code></pre>
  
  <p>As you can see, the 4th column says the class of the example. I am using the function like:</p>
  
  <pre><code>train_patterns  = A(:,:)     %HOW TO PASS A??, A(:,1:3)? A(1:size(B,1),:) ??  which????   
  train_targets   = A(:,4)     %pass the column 4 as vector of classes 
  test_patterns   = B(:,1:3)   %pass only the 3 columns
  Knn             = 3
  </code></pre>
  
  <p>So the output must be a vector <code>1 x M</code> with the prediction of all <code>B</code> examples. How can I accomplish this?</p>