Problem 138. Number of 1s in the Binary Representation of a Number
Solution Stats
Problem Comments
-
2 Comments
Can you clarify what you mean by "vectorized input"?
Nice Test cases
Solution Comments
-
5 Comments
Why does the "if max(x)"-part work in the case where x is a matrix?
I believe the "if" statement considers the first element of an array only, and ignores any additional elements. Not sure if this is documented anywhere.
@David Verelli: I've just looked into it and finally figured out why it works. According to the main description on the documentation pages, the function 'if Z' (and also 'while Z') proceeds into the conditional block when expression Z is "nonempty and contains only nonzero elements (logical or real numeric)". In other words, it doesn't consider only the first element, it actually considers all elements of Z; and when Z contains a zero, the if-block is exited/ignored. The reason why it works here in the case of test #6, is that the input matrix x = magic(10) is distributed "evenly enough" across the columns, so that every column contains at least one element greater than 63, and hence the row vector max(x) doesn't contain a 0 until the sixth (= last) time that the elements of x are reduced by the "fix(x/2)" step. So it works in this specific case, but to make this solution work generally for every case where x is a matrix, the line must be changed into "if max(x(:)),".
Sorry, there's a small error in my previous comment: I wrote "until the sixth (= last) time", but that should be "until the seventh (= last) time".
Thanks for correcting my presumption :-)
-
1 Comment
Function 'decimalToBinaryVector'is not recognized. Why not?
-
1 Comment
dec2bin(x) doesn't work for me with a square matrix x (R2009b). Is this new functionality?
Problem Recent Solvers404
Suggested Problems
-
21579 Solvers
-
2003 Solvers
-
Create matrix of replicated elements
363 Solvers
-
420 Solvers
-
5445 Solvers
More from this Author56
Problem Tags
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!