Remember that in Matlab sparse matrices are stored column-wise. Hence it is much more efficient to do column operations than to do row operations on a sparse matrix. When possible, always have two copies of the matrix A: A and AT=A’. This is important for time critical experiments.

Now let’s restrict to column operations. How do we find zero columns of a sparse matrix? There are two (or many more?) possible ways: (1) Use the `A(:,i) == 0`

test; (2) Use the `length(find(A(:,i))) == 0`

test. It turns out that the former method is way slower than the latter. Try it! Use the following codes:

`m = 10000;`

n = 10000;

density = 1e-4;

n_zero_col = 100;

% generate sparse matrix A

A = sprand(m, n, density);

% zero out some columns

idx = ceil(rand(n_zero_col,1)*n);

A(:,idx) = 0;

% two ways to find zero columns

% way 1: the `==0' construct

tic;

zero_cols = [];

for i = 1:n

if A(:,i)==0

zero_cols = [zero_cols i];

end

end

toc

% way 2: the `find' construct

tic;

zero_cols = [];

for i = 1:n

if length(find(A(:,i)))==0

zero_cols = [zero_cols i];

end

end

toc

### Like this:

Like Loading...

*Related*

## 0 Responses to “MATLAB sparse matrix: vec==0 vs. length(find(vec))==0”