Calling a function option using cellfun
Mostrar comentarios más antiguos
Hey guys,
I'm trying to use the function datestr on a cellmatrix using the option 'local'.
My code without the 'local' option looks something like this:
C = cellfun(@datestr, C, 'UniformOutput', false);
Where do I place the option in this piece of code?
I'm using Matlab2012a
Thanks
Respuesta aceptada
Más respuestas (1)
Nick Jankowski
el 10 de Nov. de 2021
realize it's been a few years, but just came across this and noticed Matlab didn't have a way of passing or implicitly expanding a parameter in cellfun (except for a very few specific functions as mentioned in the help). It looks clunky, but the following also works for parameters, passing constants, etc., as additional cell arrays without calling an anonymous function, which has a bit of a performance penalty (understanding the memory impact this could imply for very large cell arrays). I assume it can also be done for non-constant parameters, but not sure you'd see the same speedup:
abc = {magic(2), magic(3), magic(4)}
abc =
3×1 cell array
{2×2 double}
{3×3 double}
{4×4 double}
def = cellfun (@(x) sum(x,2), abc, "UniformOutput", false) % Guillaume's anonymous function method
def =
3×1 cell array
{2×1 double}
{3×1 double}
{4×1 double}
def{:}
ans =
4
6
ans =
15
15
15
ans =
34
34
34
34
def = cellfun (@sum, abc, num2cell(2*ones(size(abc))), "UniformOutput", false) % cell expansion method
def =
3×1 cell array
{2×1 double}
{3×1 double}
{4×1 double}
def{:}
ans =
4
6
ans =
15
15
15
ans =
34
34
34
34
a quick and very unscientific speed check seems to indicate it's a bit faster, although you'd want to check before scaling to large arrays, or more than one parameter
tic;
for idx = 1:100000
cellfun(@(x) sum(x,2), abc,"UniformOutput",false);
end
toc
Elapsed time is 4.017116 seconds.
tic,
for idx = 1:100000
cellfun(@sum, abc, num2cell(2*ones(size(abc))),"UniformOutput",false);
end
toc
Elapsed time is 1.217712 seconds
I would assume for nontrivial numeric parameters, you could use repmat instead of num2cell, but that seems to carry more overhead:
tic
for idx = 1:100000
cellfun(@sum, abc, repmat({2}, size(abc)),"UniformOutput",false);
end
toc
Elapsed time is 4.367002 seconds.
Categorías
Más información sobre Data Type Identification en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!