I want to apply a function to all columns in a matrix with MATLAB. For example, I’d like to be able to call smooth on every column of a matrix, instead of having smooth treat the matrix as a vector (which is the default behaviour if you call smooth(matrix)).
I’m sure there must be a more idiomatic way to do this, but I can’t find it, so I’ve defined a map_column function:
function result = map_column(m, func) result = m; for col = 1:size(m,2) result(:,col) = func(m(:,col)); end end
which I can call with:
smoothed = map_column(input, @(c) (smooth(c, 9)));
Is there anything wrong with this code? How could I improve it?
Your solution is fine.
Note that horizcat exacts a substantial performance penalty for large matrices. It makes the code be O(N^2) instead of O(N). For a 100×10,000 matrix, your implementation takes 2.6s on my machine, the horizcat one takes 64.5s. For a 100×5000 matrix, the horizcat implementation takes 15.7s.
If you wanted, you could generalize your function a little and make it be able to iterate over the final dimension or even over arbitrary dimensions (not just columns).