Can arrayfun take multi-dimensional arrays as individual arguments?

29 ビュー (過去 30 日間)
Ted
Ted 2013 年 8 月 2 日
コメント済み: Jan Siegmund 2020 年 3 月 21 日
% I have a function that takes three arguments, one of which is a vector:
[output] = function myfun(x,y,[z1 z2])
% I have a 1000x1 array 'x', 1000x1 array 'y', and 1000x2 array 'z'. Can I call this function using arrayfun, such that it will use the 1000 1x2 vectors from 'z' as individual arguments at each call, just as it uses the 1000 individual elements of 'x' and 'y'?
% The only solution I've found is a work-around making using cell arrays and constantly doing cell2mat and mat2cell conversions (very inefficient) ...
output = cell2mat(arrayfun(@(x,y,z) myfun(x,y,z,), x, y, mat2cell(z, ones(1000,1), 2));
% Your help is appreciated! Thanks!

採用された回答

Sean de Wolski
Sean de Wolski 2013 年 8 月 2 日
Just use a for-loop!
cell2mat/mat2cell/arrayfun are all slow and confusing.
  1 件のコメント
Jan Siegmund
Jan Siegmund 2020 年 3 月 21 日
This is no general solution. I am working with matrices having up to 22mio elements. Arrayfun improved the processing on a slow laptop over a for loop from 57min to just 4min. The size of data definitely plays a huge role which solution to choose over the other.

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

その他の回答 (3 件)

Cedric
Cedric 2013 年 8 月 2 日
The first thing that I would try to do is to update the function so it can take vectors/arrays.
Then I agree with Sean, Andrei, and Jan, but here is a last alternative ..
arrayfun(@(x,y,z1,z2) myfun(x,y,[z1,z2]), x, y, z(:,1), z(:,2)) ;

Andrei Bobrov
Andrei Bobrov 2013 年 8 月 2 日
編集済み: Andrei Bobrov 2013 年 8 月 2 日
I agree with Sean, but here example of use arrayfun (bad variant).
arrayfun(@(ii)myfun(x(ii),y(ii),z(ii,:)),(1:numel(x))');

Jan
Jan 2013 年 8 月 2 日
I agree with Sean (and even voted his answer): Even if the ARRAYFUN method would save some milliseconds, creating the command and later debugging will waste minutes to hours compared to simple and clean FOR loops.

カテゴリ

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

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by