Replace for loop for cell assignment based on anonymous function
13 views (last 30 days)
Show older comments
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.
0 Comments
Accepted Answer
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.
More Answers (0)
See Also
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!