Reputation: 965
I have a huge matrix in MATLAB. Now some rows contain only zeros.
Can I use the function find
to find all the rows which contain only zeros ?
Upvotes: 2
Views: 3783
Reputation: 1
n = length(matrix);
This line will give you the number of rows in a matrix.
ids = setdiff(1:n,find(sum(matrix,2)));
ids will give you the row numbers(indexes) which contain only zeros.
Upvotes: 0
Reputation: 118
If you need, you can obtain more speed (depending on your dataset) by first looking for partial zero rows (in this example length 10) and computing further with the selection of rows.
row_has_first10_zeros = sum(data(:,1:10),2);
row_has_all_zeros = sum(data(~rows,:),2);
indices = find(~row_has_first10_zeros)
indices = indices(~row_has_all_zeros)
Upvotes: 0
Reputation: 65430
You can use any
to find any rows that have non-zeros and then negate the result. We use the second input to specify that we want to apply the operation across the columns (the 2nd dimension).
row_has_all_zeros = ~any(data, 2)
If you want the indices instead of the logical array, just apply find
to the result:
indices = find(row_has_all_zeros);
Upvotes: 4