A function takes a matrix of observations, rows are observations and columns are features, and normalizes each column with X ./ sum(X). Worked for a long time without trouble. Then an input with one row came in.
sum works along the first dimension whose size isn't 1. For a 1 by n matrix that's the second dimension. So instead of a row of column sums you get one number. No error, no warning.
X = [1 2 3; 4 5 6];
sum(X) % [5 7 9]
X = [1 2 3];
sum(X) % 6, not [1 2 3]
sum(X, 1) % [1 2 3]
The division went through silently, dividing by a scalar is always allowed. Every column should have come out as 1. What came out was the row scaled so that it sums to one. Numbers between zero and one, looked normal.
The fix is an explicit dimension, sum(X, 1). Same for mean and the rest of the functions that pick their dimension from the data. The shape of a result shouldn't depend on how many rows happened to arrive. Fine, I'm writing the dimension into every call now, including the ones that only ever see big matrices.