Poll is CLOSED
Poll
Which of the following does not return the correct length (5) of v = [6,2,9,7,3]?
numel(v)
6%
length(v)
13%
width(v)
14%
nnz(v)
8%
size(v, 1)
27%
sum(v > 0)
31%
2537 votes
15 Comments
I'll argue that I terribly dislike like several of the "answers". For example,
sum(v>0)
is problematic, since it fails to produce the correct result if one or more of the elements is less than or equal to zero.
nnz(v)
fails for a similar reason in my eyes. A solution that solves a problem only for specific cases is a bad one, since one day, that code will fail and be difficult to debug. Perhaps someone might argue that
sum(v | ~v)
might have been a better choice. That succeeds as long as none of the elements of v are NaN.
Anyway, a poll like this should help teach newer users what good, robust code looks like, insted of convincing at least one new user out there that sum(v>0) might be an adequate replacement for numel(z).
ll[][]][[[][;
thank you for continuing with these!
- numel(v): Returns the number of elements in the array v. In this case, it correctly returns 5.
- length(v): Returns the number of elements along the longest dimension of the array v. Since v is a vector, length(v) correctly returns 5.
- width(v): There is no built-in function named width in MATLAB. Therefore, this option is incorrect.
- nnz(v): Returns the number of non-zero elements in the array v. Since all elements in v are non-zero, nnz(v) correctly returns 5.
- size(v, 1): Returns the size of the array v along the specified dimension. Since v is a row vector, size(v, 1) correctly returns 1.
- sum(v > 0): Returns the sum of elements in the logical array resulting from the condition v > 0. Since all elements in v are greater than 0, sum(v > 0) correctly returns 5.