Why does the full array of Matlab (X) return false in 'if X'?

I have some Matlab code that checks to see if it is an array before running, and it is skipped even if the array is 3 by 1000+.

The code is simple: if X

The array is read from the excel file using "xlsread" and gives only an error for a particular data file, but works for any other input data file that I use.

Any idea why this is?

+4
source share
2 answers

One element of the array is required to be null for this test to fail

>> A = rand(100, 3) + 1; >> if A; disp('True'); else disp('False'); end True >> A(35) = 0; >> if A; disp('True'); else disp('False'); end False 

If you want to check that the array does not contain only zeros, you can use the any keyword:

 >> A = rand(100, 3) + 1; >> A(35) = 0; >> if any(A(:)); disp('True'); else disp('False'); end True >> A = 0 * A; >> if any(A(:)); disp('True'); else disp('False'); end False 

Edit:

Sorry, as SCFrench mentions in the comments, use any(A(:)) to check each element in the array, not any(A) - this has been properly edited in my answer above.

+3
source

The any function does not work for this problem, since it treats the columns of the matrix as vectors:

 >> any([0 0 1; 0 0 1; 0 0 1]) ans = 0 0 1 

Instead, use the nnz function to count the number of nonzero entries in the matrix:

 >> nnz([0 0 1; 0 0 1; 0 0 1]) ans = 3 >> nnz([0 0 0; 0 0 0; 0 0 0]) ans = 0 
0
source

All Articles