## How to apply a cell array of function handles to an array of double

Artur Suglob

### Artur Suglob (view profile)

さんによって質問されました 2019 年 5 月 15 日

### Artur Suglob (view profile)

さんによって コメントされました 2019 年 5 月 17 日
Andrei Bobrov

### Andrei Bobrov (view profile)

さんの 回答が採用されました
I've got code:
array_double = randi (3,3)
cell_array_fuction_handles ={@(x)x*2 @(x)x*4 @(x)x*6};
for k = 1:length (array_double)
array_double(k,:) = arrayfun (cell_array_fuction_handles{k}, array_double(k,:));
end
array_double
Is there any way to replace for-loop with a vector function?
Thanks!

#### 0 件のコメント

サインイン to comment.

## 1 件の回答

2019 年 5 月 15 日

### Andrei Bobrov (view profile)

2019 年 5 月 15 日
採用された回答

out = array_double.*(2:2:6)';
General case:
out = arrayfun(@(x,y)cell_array_fuction_handles{x}(y),...
repmat((1:3)',1,3),array_double);

Artur Suglob

### Artur Suglob (view profile)

2019 年 5 月 16 日
Thanks a lot!
Actually it is somehow slower.
If I understand right, this code uses "repmat" matrix to index through function handles array and apply it (function handle) to each element of double array. So it actually works as nested for-for loop.
So I've tested some variants:
array_double = randi (100,3);
cell_array_fuction_handles ={@(x)x*2 @(x)x*4 @(x)x*6};
time1=0;array_double1=array_double;
time2=0;array_double2=array_double;
time3=0;array_double3=array_double;
time4=0;array_double4=array_double;
for kk =1:1000000
%%for loop + direct f(x)
tic
for k = 1:length (cell_array_fuction_handles)
array_double1(k,:) = cell_array_fuction_handles{k}(array_double(k,:));
end
time1=toc+time1;
%% for-for nested loop
tic
for k = 1:length (cell_array_fuction_handles)
for j = 1:length (array_double)
array_double2(k,j) = cell_array_fuction_handles{k}(array_double(k,j));
end
end
time2=toc+time2;
%% for loop + arrayfun
tic
for k = 1:length (cell_array_fuction_handles)
array_double3(k,:) = arrayfun (cell_array_fuction_handles{k}, array_double(k,:));
end
time3=toc+time3;
%% only arrayfun
tic
array_double4 = arrayfun(@(x,y)cell_array_fuction_handles{x}(y),repmat((1:3)',1,3),array_double);
time4=toc+time4;
end
time1
time2
time3
time4
So it looks like the first is the best.

2019 年 5 月 16 日
Well that is what I mentioned!!
Artur Suglob

### Artur Suglob (view profile)

2019 年 5 月 17 日
Thanks!

サインイン to comment.

Translated by