Is a man allowed to waste his seed for medical reasons, for example if a couple is having difficulty conceiving and the fertility specialists are requesting a sample.
In Sefer Nishmat Avraham- Even Haezer Siman 23 this very question is asked. The Tzitz Eliezer sums up as follows: A husband may produce sperm for examination after his wife has been thoroughly tested. However the way the sperm should should be halachically obtained is as follows: 1) The simplest way would be a post-coital sample; this would be permitted by almost all poskim. 2) If this is not possible or unsatisfactory, it should be obtained by coitus interruptus(as preferred by the Zekan Aharon). 3) If this is technically difficult, a condom can be worn during coitus; other poskim, however prefer this to coitus interruptus(among them Rav Auerbach zt'l) 4) If this is also not possible for whatever reason, it may be obtained by masturbation. Preferably, the doctor should obtain it using an instrument, but if this is not possible, the husband may obtain it himself.(This is the ruling of the Ahiezer but it is forbidden by the Igrot Moshe)
In regard to how long a couple must wait before the Husband's sperm may be examined: The Minchat Yitzchak writes that this may only been done after ten years of marriage; the Igrot Moshe writes five years; whereas the Chazon Ish was said to have permitted it after two years.