title: Finding the best threshold level without a for loop in MATLAB
body: <p>Let A and B be two matrices of the same size. For a matrix M, let ht(M,t) threshold all the entries of M by t. That is All entries whose absolute value is less than t are set to 0. Suppose I want to find the optimal threshold t such that norm(ht(A,t)-B,'fro')^2 is minimized.</p>
  
  <p>The only way that I can see to do this is deficient: do a for loop over the unique values of A and threshold A and setting C=ht(A,t)-B, compute sum(sum(C.*C)).</p>
  
  <p>This is just too slow when A is large. I have considered sorting the elements of A and finding some efficient way to set a few entries to zero at a time, but I'm not sure this can all be done without a for loop.</p>
  
  <p>Is there a way to do it?</p>
  
  <p>Here's a very simple example (so simple a for loop works easily in this case):</p>
  
  <pre><code>B =
  
       0.101508820368332                         0
                       0         0.301996943246957
  
  Set
  
  A=B+.1*ones(2)
  
  A =
  
           0.201508820368332                       0.1
                         0.1         0.401996943246957
  </code></pre>
  
  <p>Simple inspection shows that if we zero out the off-diagonal entries of A we minimize the difference between A and B. There are 3 possible threshold values, given by unique(A)=[.1,.2015,.402]. Given a potential threshold value t, we can hard threshold A by:</p>
  
  <pre><code>function [A_thresholded] = ht(A,t)
  %
  A_thresholded = A .* (abs(A)&gt;t);
  </code></pre>