1

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

Shawn C.
  • 6,446
  • 3
  • 34
  • 38

2 Answers2

3

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.

Play with it on TryAPL!

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
∇

Try it online!

Adám
  • 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
1

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)

Lobachevsky
  • 1,222
  • 9
  • 17