home *** CD-ROM | disk | FTP | other *** search
/ APDL Eductation Resources / APDL Eductation Resources.iso / programs / electronic / rlab / TestMatrix / sparsify_r < prev    next >
Encoding:
Text File  |  1994-12-20  |  1.2 KB  |  48 lines

  1. //-------------------------------------------------------------------//
  2.  
  3. // Synopsis:    Randomly sets matrix elements to zero.
  4.  
  5. // Syntax:    S = sparsify ( A , P )
  6.  
  7. // Description:
  8.  
  9. //    S is A with elements randomly set to zero (S = S' if A is
  10. //    square and A = A', i.e. symmetry is preserved). Each element
  11. //    has probability P of being zeroed. Thus on average 100*P
  12. //    percent of the elements of A will be zeroed. 
  13.  
  14. //    Default: P = 0.25. 
  15.  
  16. //    This file is a translation of sparsify.m from version 2.0 of
  17. //    "The Test Matrix Toolbox for Matlab", described in Numerical
  18. //    Analysis Report No. 237, December 1993, by N. J. Higham.
  19.  
  20. //-------------------------------------------------------------------//
  21.  
  22. sparsify = function ( A , p )
  23. {
  24.   local (A, p)
  25.  
  26.   if (!exist (p)) { p = 0.25; }
  27.   if (p < 0 || p > 1) {
  28.     error("Second parameter must be between 0 and 1 inclusive.");
  29.   }
  30.  
  31.   // Is A square and symmetric?
  32.   symm = 0;
  33.   if (min(size(A)) == max(size(A))) {
  34.     if (norm(A-A',"1") == 0) { symm = 1; }
  35.   }
  36.  
  37.   if (!symm)
  38.   {
  39.     A = A .* (rand(size(A)) > p);        // Unsymmetric case
  40.   else
  41.     A = triu(A,1) .* (rand(size(A)) > p);    // Preserve symmetry
  42.     A = A + A';
  43.     A = A + diag( diag(A) .* (rand(size(diag(A))) > p) );
  44.   }
  45.  
  46.   return A;
  47. };
  48.