0
$\begingroup$

I wrote a module which hopes to count the number of $1$'s in a given vector

mycount[v_]:=Module[{v0=v},s=0;Do[If[v0[[i]]=1,s=s+1],{i,1,Length[v0]}];s]

However, no matter how I change it around, it returns the number $0$ for the example vector {1,1,1,2} I used, can someone point out what is wrong becauuse I cannot see it?

$\endgroup$
5
  • 1
    $\begingroup$ mycount[v_] := Module[{v0 = v, s = 0}, Do[If[v0[[i]] == 1, s = s + 1], {i, 1, Length[v0]}]; s] $\endgroup$
    – Syed
    Oct 18, 2021 at 20:25
  • 4
    $\begingroup$ Please show a complete MWE including the call itself. btw, there is a function called Count in Mathematica already. $\endgroup$
    – Nasser
    Oct 18, 2021 at 20:26
  • $\begingroup$ @Syed Thank you so much! $\endgroup$
    – JBuck
    Oct 18, 2021 at 20:33
  • $\begingroup$ @Nasser Nvm, I already solved it thanks to the comment above. I knew of the Count function, I was just practising creating modules and doing loops. Thanks anyway! $\endgroup$
    – JBuck
    Oct 18, 2021 at 20:35
  • 2
    $\begingroup$ Count[{1, 1, 1, 2}, 1] would count 1s. I think you should look at the book written by the inventor himself for beginners. $\endgroup$
    – Syed
    Oct 18, 2021 at 20:35

1 Answer 1

4
$\begingroup$

Here's a faster alternative that uses vectorized operations:

mycount2[v_] := Length[v] - Total[Unitize[v - 1]]

Compare (with v0[[i]] = 1 changed to v0[[i]] == 1):

list = RandomInteger[{1, 3}, 10^6];

mycount[list] // AbsoluteTiming
{0.680935, 333888}
mycount2[list] // AbsoluteTiming
{0.012579, 333888}

And a built in function:

Count[list, 1] // AbsoluteTiming
{0.033939, 333888}
$\endgroup$
1
  • $\begingroup$ Interesting that the user-defined mycount2 outperforms built-in Count here. $\endgroup$
    – murray
    Oct 19, 2021 at 15:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.