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

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?

4 Comments
madhan ravi on 6 Sep 2018

Direct link to this comment

Cancel Copy to Clipboard

Direct link to this comment

Cancel Copy to Clipboard upload your code and datas Jeongseop Lee on 6 Sep 2018

Direct link to this comment

Cancel Copy to Clipboard

Direct link to this comment

Cancel Copy to Clipboard

Here is it, as an example. The actual function is complicated and there is a little room for modification but for illustration I will just define a much simpler operation that is essentially equivalent.

% example for "A" A = [1 2 3 4;5 6 7 8;9 10 11 12]; % definition for "Func" function Result = Func(X) Result = sum(X) Paolo on 6 Sep 2018

Direct link to this comment

Cancel Copy to Clipboard

Direct link to this comment

Cancel Copy to Clipboard If B is the output matrix, what do you want B to be for that A? Jeongseop Lee on 6 Sep 2018

Direct link to this comment

Cancel Copy to Clipboard

Direct link to this comment

Cancel Copy to Clipboard Edited: Jeongseop Lee on 6 Sep 2018

The actual calculation of B is much more complicated that takes cascades of multiple functions and B is an optimization fitness product for given population A in neural network. But all this detail is highly irrelevant for my question here. I just want a simple, elegant way that is non-iterative definition that applies a function to each column of a given matrix for all columns without iterative definition.

Accepted Answer

Matt J on 6 Sep 2018

Direct link to this answer

Cancel Copy to Clipboard

Direct link to this answer

Cancel Copy to Clipboard Edited: Matt J on 6 Sep 2018

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: