Apply the same function into several columns

9 ビュー (過去 30 日間)
MAK
MAK 2019 年 4 月 4 日
回答済み: MAK 2019 年 4 月 4 日
Hi!
I have a matrix A (50x50), and every column of the 50 are different subjects. I want to apply the same function to each column separetely and save the answers of the function into a different matrix B(50x1) The function is exactly the same, all that changes is the data on which the function is performed on.
How can I do it?
Thanks!

採用された回答

Guillaume
Guillaume 2019 年 4 月 4 日
編集済み: Guillaume 2019 年 4 月 4 日
Use a loop:
B = zeros(1, size(A, 2));
for column = 1 : size(A, 2)
B(column) = yourfunction(A(:, column));
end
Or you can use cellfun, which is just a loop in disguise:
B = cellfun(@yourfunction, num2cell(A, 1));
edit: That's assuming the function cannot already operate on the columns of the whole matrix, as pointed out by Star.
  2 件のコメント
Jos (10584)
Jos (10584) 2019 年 4 月 4 日
I suggest the use of arrayfun, rather than cellfun, assuming yourfunction(V) returns a scalar value for a vector V:
B = arrayfun(@(k) yourfunction(A(:,k)) , 1:size(A, 2))
Guillaume
Guillaume 2019 年 4 月 4 日
I find the cellfun more readable personally. Ultimately, you have the cost of an anonymous function call vs the cost of splitting the matrix into a cell array.

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

その他の回答 (1 件)

MAK
MAK 2019 年 4 月 4 日
Thanks to all!!

カテゴリ

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