How we count number of matrices with respect to some condition?

1 view (last 30 days)
I have 1000 rows
for i=1:1000
B=A(i,:);
C=reshape(B,4,4);
D=bsxfun(@minus,C,max(C(:)))
end
Now I have 1000 D matrices , How can I check that
1- How many of D matrices are Null matrix (having all the entries are zero);
2- How many of D matrices have all the 4 distinct column;
3-How many of D matrices have 3 distinct column;
4- How many of D matrices have 2 distinct column;
5- How many of D matrices have 0 on its diagonal ;
6-How many of D matrices have non-zero entry on its diagonal.
Thanking for anticipation
  2 Comments
Guillaume
Guillaume on 7 Feb 2018
Now I have 1000 D matrices
Well, actually, you have only one D matrix that you overwrite 999 times, leaving only the one created at step i = 1000.
D=bsxfun(@minus,C,max(C(:)))
That's a very convoluted way of doing
D = C - max(C(:));
Now if you were to get rid of the loop and operate on the whole A at once which would be a lot faster, and indeed create your 1000 matrices, then yes bsxfun could be useful:
D = permute(reshape(A.', 4, 4, []), [2 1 3]); %creates a 4x4x1000 matrix
D = bsxfun(@minus, D, max(max(D, [], 1), [], 2)));
Ammy
Ammy on 7 Feb 2018
I have a lots of matrices in which some matrices are null matrices, How can I get total number of null matrices.

Sign in to comment.

Answers (1)

KSSV
KSSV on 7 Feb 2018
1- How many of D matrices are Null matrix (having all the entries are zero);
Try using nnz()...nnz gives you number of non-zero sin the matrix.
2- How many of D matrices have all the 4 distinct column;
Try using unique. Read about it. You can use unique along rows and columns.
3-How many of D matrices have 3 distinct column;
Read abiut unique
4- How many of D matrices have 2 distinct column;
Read about unique
5- How many of D matrices have 0 on its diagonal ;
Read about diag. This gives you diagonal elements. And then you can use nnz.
6-How many of D matrices have non-zero entry on its diagonal.
Read about diag and nnz.
  2 Comments
Ammy
Ammy on 7 Feb 2018
nnz counts the number of entries in a matrix, but I want to count number of matrices having all the entries 0.
Steven Lord
Steven Lord on 7 Feb 2018
The nnz function counts the Number of NonZero elements in the array. It ignores zero elements.
When all elements are non-zero, nnz is the same as numel which returns the NUMber of ELements.
A = magic(4)
nnzA = nnz(A)
nA = numel(A)
When some elements are non-zero and some are zero, nnz and numel return different values.
B = eye(4)
nnzB = nnz(B)
nB = numel(B)
When all elements are zero, nnz should return ...
C = zeros(4)
nncZ = nnz(C)
nC = numel(C)

Sign in to comment.

Categories

Find more on Operating on Diagonal Matrices in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!