Return the number of 1s in the (unsigned integer) binary representation of a number. This function should be able to provide vectorized input and return an output with the same dimensions as the input.
in = 215
out = 6
Can you clarify what you mean by "vectorized input"?
Nice Test cases
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 :-)
Function 'decimalToBinaryVector'is not recognized. Why not?
dec2bin(x) doesn't work for me with a square matrix x (R2009b). Is this new functionality?
Return the largest number that is adjacent to a zero
Project Euler: Problem 2, Sum of even Fibonacci
matrix of natural number
Next Higher Power of B
Great Circle Distance
Inhomogenous Depth Scale Interpolation
Square Digits Number Chain Terminal Value (Inspired by Project Euler Problem 92)
Choose a web site to get translated content where available and see local events and offers. Based on your location, we recommend that you select: .
You can also select a web site from the following list:
Select the China site (in Chinese or English) for best site performance. Other MathWorks country sites are not optimized for visits from your location.
Contact your local office