This works relatively fast in matlab, but is really slow on R. There is a lot of copying, but maybe also C++ is an alternative.