MATLAB: Apply function to each column of matrix for all columns without for loop

computationfor loop

Hi all,
I have a function "Func(X)" which operations on n-by-1 single column matrix "X" and outputs a scalar quantity. I also have a n-by-m matrix "A" that I would like to apply "Func" for all m columns in "A" and obtain 1-by-m matrix, say B, as a result without using for loop or any iterative definitions. What is the best way to proceed with this?

Best Answer

There is no general way that is more efficient than a for-loop, but if you are just trying to hide the loop, then you can do things like this:
B=cell2mat( arrayfun(@(i) Func(A(:,i)) , 1:size(A,2), 'uni',0) );
or
B = splitapply(@Func,A,1:size(A,2));