fixed matrix insertion logic