Replace for loop for cell assignment based on anonymous function

13 views (last 30 days)
I have a anonymous function of x which outputs a matrix. I have an array of 'x' values for which I want to store output of anonymous function in individual cell using for loop. I was wondering if this for loop can be replaced for better execution efficiency. Sample code below:
anonfunc = @(x) [zeros(2); blkdiag(1-x, 1+x)];
input = [1,5,7]';
output = cell(1,3);
for i = 1:3
output{i} = anonfunc(input(i));
end
I want to replace for loop with single command such as:
output{1:3} = anonfunc(input); %I am well aware this command doesn't work and is written to give idea of what I want.
Thanks in Advance.

Accepted Answer

csamoa
csamoa on 25 Jun 2021
You can use arrayfun with 'UniformOutput' set to false, which will output a cell-array of the results of the anonfunc on the values of your input vector.
The orientation of the output cell-vector depends on the orientation of the input vector.
The optional transpose changes the orientation.
anonfunc = @(x) [zeros(2); blkdiag(1-x, 1+x)];
input = [1,5,7]';
tic
output = cell(1,3);
for i = 1:3
output{i} = anonfunc(input(i));
end
toc
tic
output2 = arrayfun(anonfunc, input, 'UniformOutput', false)';
toc
The gain in speed varied, e.g.:
Elapsed time is 0.003087 seconds.
Elapsed time is 0.001898 seconds.
  1 Comment
Nauman Haider
Nauman Haider on 25 Jun 2021
Thanks. The suggestion does output what I was looking for. However, I was expecting much faster performance in my code but it was not as much as I thought it will be. Thanks once again for your help @csamoa.

Sign in to comment.

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!