Replace for loop for cell assignment based on anonymous function

13 次查看(过去 30 天)
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.

采纳的回答

csamoa
csamoa 2021-6-25
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 个评论
Nauman Haider
Nauman Haider 2021-6-25
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.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by