added merge matrix function