finally working!
writing output matrix