For example I have a vector 'H2DH2DH'
, is there a way to count the number of 'H'
scalars that appear?

- 6,446
- 3
- 34
- 38

- 41
- 2
-
@ShawnC. Why the removal of tags? – Adám Mar 13 '18 at 13:29
2 Answers
I assume you mean you have the character vector 'H2DH2DH'
and want to count how many scalar 'H'
characters are in there.
'H'='H2DH2DH
will give you a Boolean vector indicating where the desired characters are. +/'H'='H2DH2DH'
will sum that, and give you the count.
You can also define a generalised function which takes a scalar as left argument and a vector as right argument and counts the number of occurrences of the scalar in the vector.
Some APL systems (e.g. Dyalog, GNU, and ngn) will let you write CountIn←{+/⍺=⍵}
where ⍺
stands for the left argument, and ⍵
for the right argument. Try it online! The remaining systems (e.g. APLX, APL+WIN, and APL2) will have you type:
∇ count←char CountIn text
count←+/char=text
∇

- 6,573
- 20
- 37
-
@RichardAdams: can you pls. accept the answer, so that the question is no longer shown as "open" (just tick the check-mark next to the reply). – MBaas Mar 26 '18 at 07:50
Or, if you prefer, to count the occurrences using inner product:
'H'+.='H2DH2DH'
(Years ago, on other implementations, +/'H'='H2DH2DH'
may have been slightly faster, perhaps this is still true)

- 1,222
- 9
- 17