We describe an algorithm for optimizing the parameters of sandwich X-ray detectors in relation to the recognition of materials by the dual energy method. The application of the algorithm is illustrated by a concrete example in which we obtain the thicknesses of the first detector and the intermediate filter (that are part of a sandwich detector) that are optimal for detecting explosives for the given materials of the first detector (CsI) and the intermediate filter (Cu).