working on matrix loop algorithm