How to call a function with rows of a matrix?

3 ビュー (過去 30 日間)
UCL student
UCL student 2014 年 10 月 29 日
編集済み: Stephen23 2014 年 10 月 30 日
Hey,
I would like to vectorize a function call that I call with rows of a matrix. How can I implement it without a for loop?
Thanks.
  5 件のコメント
Julia
Julia 2014 年 10 月 30 日
編集済み: Julia 2014 年 10 月 30 日
Your Res will be overwritten in each loop iteration.
If your function aFunction takes only vectors as its input and has a single number as output, I don't see a method to omit the loop.
UCL student
UCL student 2014 年 10 月 30 日
I would like Res to be a vector of results.

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

回答 (2 件)

the cyclist
the cyclist 2014 年 10 月 30 日
編集済み: the cyclist 2014 年 10 月 30 日
Res = zeros(10000,1);
for looper=1:10000
Res(looper) = aFunction(Mat(looper,:),Mat2(looper,:))
end
Note that the first line, preallocating memory is important for the loop to operate efficiently.
If you want to post your aFunction code, it might be possible to identify a way to eliminate the loop entirely.

Stephen23
Stephen23 2014 年 10 月 30 日
編集済み: Stephen23 2014 年 10 月 30 日
One easy way is to use num2cell to split the numeric arrays into rows/columns/..., and then cellfun on the resulting cell arrays (change the variable names to suit):
out = cellfun(@fun,num2cell(M1,2),num2cell(M2,2),...);
This method assumes that @fun operates on a vector and returns a scalar.
Alternatively you could use the table data class, which supports the function rowfun.

カテゴリ

Help Center および File ExchangeCell Arrays についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by