MATLAB: Change default behavior of cellfun to ‘UniformOuput’ = false

cellfundefaultsMATLAB

Is there a way to make 'UniformOuput' = false the default for cellfun and functions like it?

Best Answer

I really wish this was an option too! I use cellfun all the time, and almost always with cell outputs required. This is one of those errors that bugs me because the solution is so easily automated. It bugs me enough that I wrote a kinda kludgy wrapper function to handle both cases; it just runs cellfun, and adds the 'UniformOutput'=0 flag if it fails the first time.
function varargout = celllfun(varargin)
varargout = cell(nargout,1);
try
[varargout{:}] = cellfun(varargin{:});
catch ME
if strcmp(ME.identifier, 'MATLAB:cellfun:NotAScalarOutput')
[varargout{:}] = cellfun(varargin{:}, 'uni', 0);
else
rethrow(ME);
end
end
This returns an array if possible, and a cell array otherwise:
>> a = celllfun(@(x) x(1:2), num2cell(rand(10,2),1))
a =
1×2 cell array
[2×1 double] [2×1 double]
>> a = celllfun(@(x) x(1), num2cell(rand(10,2),1))
a =
0.18675954426984 0.173883139944506
Here I've simply added an extra letter to the function name, so cellfun and celllfun coexist. You could use this function_handle function to do a true shadowing of the built-in to get this try-catch behavior as the default whenever cellfun is called.