Replace for loop for cell assignment based on anonymous function
12 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
Nauman Haider
il 25 Giu 2021
Commentato: Nauman Haider
il 25 Giu 2021
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 Commenti
Risposta accettata
csamoa
il 25 Giu 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.
Più risposte (0)
Vedere anche
Categorie
Scopri di più su Loops and Conditional Statements in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!