refactored loops to matlab style matrix functions