开发者

How can I test submatrices of a matrix to see if they contain all zeroes?

I've a large matrix, say A[1,10,10000], which contains 10000 1-by-10 submat开发者_高级运维rices. I want to check each of these submatrices to find which ones contain all zeroes. How can I do this?


You could do this using the functions ALL and SQUEEZE:

allZeroIndex = squeeze(all(all(A == 0,2),1));

And this will give you a logical vector allZeroIndex that has the same length as the third dimension of A and contains a 1 (i.e. true) for matrices that have all zeroes and 0 (i.e. false) for matrices that contain non-zero values.


NOTE: Of course the above would really only be appropriate for a matrix of integer values. If there is the chance that you will have floating point values in A, then odds are good that you may never get exactly 0 for a value. In such a case, you need to check for values that are within some threshold of 0, like so:

allNearZeroIndex = squeeze(all(all(abs(A) < 1e-10,2),1));


The simple answer is to use nnz.

if nnz(A) == 0
  disp('Yup, this is one really boring matrix.')
end


Instead of all, you can also use sum:

allZero = sum(sum(A==0)); % will be non-zero if there are non-zero values


I think using nnz is probably the best bet, but didn't know about that until now. Instead I would have used unique(): if unique(A)==0 ...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜