[ACCEPTED]-What's the best way to iterate through columns of a matrix?-enumeration
The MATLAB "for" statement actually loops 8 over the columns of whatever's supplied 7 - normally, this just results in a sequence 6 of scalars since the vector passed into 5 for (as in your example above) is a row 4 vector. This means that you can rewrite 3 the above code like this:
function result = map_column(m, func)
result = [];
for m_col = m
result = horzcat(result, func(m_col));
end
If func does not 2 return a column vector, then you can add 1 something like
f = func(m_col);
result = horzcat(result, f(:));
to force it into a column.
Your solution is fine.
Note that horizcat 10 exacts a substantial performance penalty 9 for large matrices. It makes the code be 8 O(N^2) instead of O(N). For a 100x10,000 7 matrix, your implementation takes 2.6s on 6 my machine, the horizcat one takes 64.5s. For 5 a 100x5000 matrix, the horizcat implementation 4 takes 15.7s.
If you wanted, you could generalize 3 your function a little and make it be able 2 to iterate over the final dimension or even 1 over arbitrary dimensions (not just columns).
Maybe you could always transform the matrix 3 with the ' operator and then transform the 2 result back.
smoothed = smooth(input', 9)';
That at least works with the 1 fft function.
A way to cause an implicit loop across the 10 columns of a matrix is to use cellfun. That 9 is, you must first convert the matrix to 8 a cell array, each cell will hold one column. Then 7 call cellfun. For example:
A = randn(10,5);
See that here 6 I've computed the standard deviation for 5 each column.
cellfun(@std,mat2cell(A,size(A,1),ones(1,size(A,2))))
ans =
0.78681 1.1473 0.89789 0.66635 1.3482
Of course, many functions in 4 MATLAB are already set up to work on rows 3 or columns of an array as the user indicates. This 2 is true of std of course, but this is a 1 convenient way to test that cellfun
worked successfully.
std(A,[],1)
ans =
0.78681 1.1473 0.89789 0.66635 1.3482
Don't forget to preallocate the result matrix 4 if you are dealing with large matrices. Otherwise 3 your CPU will spend lots of cycles repeatedly 2 re-allocating the matrix every time it adds 1 a new row/column.
If this is a common use-case for your function, it 9 would perhaps be a good idea to make the 8 function iterate through the columns automatically 7 if the input is not a vector.
This doesn't 6 exactly solve your problem but it would 5 simplify the functions' usage. In that case, the 4 output should be a matrix, too.
You can also 3 transform the matrix to one long column 2 by using m(:,:) = m(:)
. However, it depends on your function 1 if this would make sense.
More Related questions
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.