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

108 ビュー (過去 30 日間)
Jeongseop Lee
Jeongseop Lee 2018 年 9 月 6 日
編集済み: Greg Heath 2018 年 9 月 7 日
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?
  4 件のコメント
Paolo
Paolo 2018 年 9 月 6 日
If B is the output matrix, what do you want B to be for that A?
Jeongseop Lee
Jeongseop Lee 2018 年 9 月 6 日
編集済み: Jeongseop Lee 2018 年 9 月 6 日
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.

サインインしてコメントする。

採用された回答

Matt J
Matt J 2018 年 9 月 6 日
編集済み: Matt J 2018 年 9 月 6 日
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));

その他の回答 (1 件)

Greg Heath
Greg Heath 2018 年 9 月 7 日
編集済み: Greg Heath 2018 年 9 月 7 日
The MATLAB CONVENTION is that functions operate on matrix columns.
Therefore, it is only with user-defined functions that operations on rows occur.
Hope this helps.
Thank you for formally accepting my answer
Greg

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by