Certainly it can be done much easier. Instead of this
yth_row = mean(yth_rows);
This has the advantage that you could even do it for n and the mean will work no matter how many lines you average, you could even do it in a single line, I did it in two to illustrate above, but this works as well
n = 2;
Hope that answers the question.