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

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!

 Risposta accettata

Andrei Bobrov
Andrei Bobrov il 15 Mag 2019
Modificato: Andrei Bobrov il 15 Mag 2019
In your case:
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);

4 Commenti

arrayfun() is slower than a loop
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.
Well that is what I mentioned!!

Accedi per commentare.

Più risposte (0)

Categorie

Scopri di più su Loops and Conditional Statements in Centro assistenza e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by