The present invention introduces a method, apparatus and computer program for magnetic resonance imaging or magnetoencephalography applications in order to control currents of a coil assembly (20), and thus achieving desired magnetic fields precisely in the measuring volume (21). The approach is an algebraic method where a field vector is generated for the test currents of each coil (20). Vector and matrix algebra is applied and a linear set of equations is formed. Field components and their derivatives up to the desired order can be taken into account. Principal component analysis or independent component analysis can be applied for determination of the dominant external interference components. By checking the condition value for the matrix (33, 45), it is possible to investigate whether a reasonable solution of currents for desired magnetic fields is possible to achieve. Finally, solved currents can be installed into a current supply unit (29) feeding the coils of the assembly (20). The invention can be applied as an active compensation feature for different interference shapes in the MEG application (25), or for the precise creation of the fields and gradients in the MRI application (24).