Replace for loop for cell assignment based on anonymous function

조회 수: 12 (최근 30일)
Nauman Haider
Nauman Haider 2021년 6월 25일
댓글: Nauman Haider 2021년 6월 25일
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