-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmapToCell.m
More file actions
51 lines (41 loc) · 1.58 KB
/
mapToCell.m
File metadata and controls
51 lines (41 loc) · 1.58 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
function [C1, varargout] = mapToCell(f, varargin)
%MAPTOCELL Like cellfun and arrayfun, but always returns a cell array
% [C1, ...] = MAPTOCELL(FUN, A1, ...) applies the function FUN to
% each element of the variable number of arrays A1, A2, etc, passed in. The
% outputs of FUN are used to build up cell arrays for each output.
%
% Unlike MATLAB's cellfun and arrayfun, MAPTOCELL(..) can take a mixture
% of standard and cell arrays, and will always output a cell array (which
% for cellfun and array requires the 'UniformOutput' = false flag).
%
% Part of Burgbox
% 2013-01 CB created
% TODO: ensure all input array arguments have the same size and shape
nelems = numel(varargin{1});
inSize = size(varargin{1});
nout = max(nargout, min(nargout(f), 1));
% function that converts non-cell arrays to cell arrays
ensureCell = @(a) iff(~iscell(a), @() num2cell(a), a);
% make sure all input arguments are cell arrays...
varargin = cellfun(ensureCell, varargin, 'UniformOutput', false);
% ...so now we can concatenate them and treat them as cols in a table and
% read them row-wise
catarrays = cat(ndims(varargin{1}), varargin{:});
linarrays = reshape(catarrays, nelems, numel(varargin));
fout = cell(nout, 1);
arg = cell(nout, nelems);
% iterate over each element of input array(s), apply f, and save each (variable
% number of) output.
for i = 1:nelems
[fout{1:nout}] = f(linarrays{i,:});
arg(1:nout,i) = fout(1:nout);
end
varargout = cell(nargout - 1, 1);
for i = 1:nout
if i == 1
C1 = reshape(arg(i,:), inSize);
else
varargout{i - 1} = reshape(arg(i,:), inSize);
end
end
end