comparison toolbox/sparsify.m @ 2:c124219d7bfa draft

Re-add the 1995 toolbox after noticing the statement in the ~higham/mctoolbox/ webpage.
author Antonio Pino Robles <data.script93@gmail.com>
date Thu, 07 May 2015 18:36:24 +0200
parents 8f23314345f4
children
comparison
equal deleted inserted replaced
1:e471a92d17be 2:c124219d7bfa
1 function A = sparsify(A, p)
2 %SPARSIFY Randomly sets matrix elements to zero.
3 % S = SPARSIFY(A, P) is A with elements randomly set to zero
4 % (S = S' if A is square and A = A', i.e. symmetry is preserved).
5 % Each element has probability P of being zeroed.
6 % Thus on average 100*P percent of the elements of A will be zeroed.
7 % Default: P = 0.25.
8
9 if nargin < 2, p = 0.25; end
10 if p<0 | p>1, error('Second parameter must be between 0 and 1 inclusive.'), end
11
12 % Is A square and symmetric?
13 symm = 0;
14 if min(size(A)) == max(size(A))
15 if norm(A-A',1) == 0, symm = 1; end
16 end
17
18 if ~symm
19 A = A .* (rand(size(A)) > p); % Unsymmetric case
20 else
21 A = triu(A,1) .* (rand(size(A)) > p); % Preserve symmetry
22 A = A + A';
23 A = A + diag( diag(A) .* (rand(size(diag(A))) > p) );
24 end