MATLAB Answers

Functional programming construct to expand cell array into arguments for other functions without using an intermediate variable in the (user) code?

4 ビュー (過去 30 日間)
I'm looking for a functional programming construct. The construct should let me use a cell array, e.g. returned from a function, as separate arguments to another function -- without (the user) having to create an intermediate variable.
Example: Let's say I have two objects (tables), T1 and T2, for which I'd like to compare different properites (e.g. size, variable names). I could do it as follows (doing the example for just one property):
property_1 = @(T) T.Properties.VariableNames;
C = cellfun(property_1, { T1, T2 }, 'UniformOutput', 0); % (1)
assert(isequal(C{:})); % (2)
However, I'd like a way to achieve (1) and (2) without assigning to the intermediate variable, 'C'. Unfortunately the following code doesn't work:
assert(isequal(cellfun(varnames, { T1, T2 }, 'uni', 0){:}));
Is it possible to write a helper function 'foo' that would allow this code:
Or must there instead be another type of helper function, 'bar', that's used along the following lines:
assert(bar(@isequal, result))
function [varargout] = bar(fcn, C)
[varargout{1:nargout}] = fcn(C{:});
If I can only do the latter, any suggestions for the name of 'bar'?
  2 件のコメント
Christian Ridderström
Christian Ridderström 2021 年 8 月 13 日
Yes, there are reasons why I'd like an alternative to the strategy above. That strategy is fine when implementing the tests in a .m-file. I would use the second alternative though and generalise it into something like the following to support multiple arguments and choosing between e.g. 'isequal' and 'isequaln':
% Example:
% assert_comparable_properties(@size, @isequal, T1, T2)
% Caveat: Untested code!
function assert_comparable_properties(property, comparator, varargin)
if isequal(comparator, []), comparator = @isequal; end
D = cellfun(property, varargin, 'uni', 0);
assert(comparator(D{:}), 'Comparison of objects failed')
% If 'comparator' only takes two arguments, use this for loop:
% for ii = 2:numel(D)
% assert(comparator(D{ii-1}, D{ii}), ...
% 'Comparison of objects: %d and %d failed', ii-1, ii)
% end
However, while experimenting and running tests on the command line, it's convenient if I can use anonymous functions. (If I remember correctly, you can't use 'function() ... end' on the MATLAB command line).
Then I just generally like to learn alternative ways of doing things - you never know when it's useful.
Finally, I know I have on several other occasions encountered situations where I'd like to expand e.g. output of cellfun(). I think I e.g. wanted to do something like:
C = cellfun(...)
y = vertcat(C{:})
Note: I don't remember the details, but I think I was generating combinations of parameter sets to be used for running suites of Simulink simulations. I.e. I had a bunch of parameters for which a small subset of the parameter could only take on a few discrete values and I wanted to generate all combinations of all such parameters. I then ended up writing a framework that turned out ok, except I missed being able to do the above.



Stephen 2021 年 8 月 12 日
編集済み: Stephen 2021 年 8 月 12 日
The closest is to use the new syntax which allows dot indexing directly into function outputs:
For example:
123 456 789
function S = testfun()
S(1).X = 123;
S(2).X = 456;
S(3).X = 789;
Otherwise the reason why your approach will not work is already explained in detail in this comment (and thread):
  5 件のコメント
Christian Ridderström
Christian Ridderström 2021 年 8 月 14 日
Note: Does not work in R2018b, but does work in R2020b.


その他の回答 (2 件)

J. Alex Lee
J. Alex Lee 2021 年 8 月 13 日
編集済み: J. Alex Lee 2021 年 8 月 13 日
I am still not sure why you can't just have your generalized comparator function saved as a function somewhere on your path so you can reference it often...but anyway, "apply_expand" is still an intermediary, though you do accomplish it inline...
With @Stephen Cobeldick's insight, I thnk you could as well do (it would be just as cumbersome but you can at least remove one anonymous function definition)
isequal(cell2struct(cellfun(property_1, { T1, T2 }, 'UniformOutput', 0),"myprop").myprop)
To me, it all points to the more upstream question of why you can dot-index, but not brace-index into function doesn't seem at all silly to expect that it should work, and it seems to me that many questions along the lines of the actual question here (as well as the linked one) might ultimately derive from this inability.
  2 件のコメント
Christian Ridderström
Christian Ridderström 2021 年 8 月 14 日
Seems to work well.
For readability I created and used a helper 'cellfun_s()' as follows:
% Helper function like 'cellfun', but with the output placed in the field
% '.as_list' of a struct array.
cellfun_s = @(varargin) cell2struct(cellfun(varargin{:}, 'UniformOutput', 0), 'as_list');
% Create some objects to be compared
objs = { table(rand(5)), table(rand(5)), table(rand(5)) };
% Make a smörgåsbord of ways to get aspects/properties from the objects (to be compared)
getters = {@size, @(T) T.Properties.VariableNames};
% Compare the objects with regards to the first aspect/property
comparison_result_1 = isequal(cellfun_s(getters{1}, objs).as_list)
comparison_result_1 = logical
The approach also scales for multiple comparisons:
% Compare all (2) aspects for all (3) the objects
comparison_results = cellfun(@(pg) isequal(cellfun_s(pg, objs).as_list), getters)
comparison_results = 1×2 logical array
1 1


Christian Ridderström
Christian Ridderström 2021 年 8 月 13 日
Here is an answer that follows the last approach in my question, using the name 'apply_expand' for 'bar':
property_1 = @(T) T.Properties.VariableNames;
apply_expand = @(fcn, C) fcn(C{:});
assert(apply_expand(@isequal, cellfun(property_1, { T1, T2 }, 'UniformOutput', 0)));
Below is an exanded example, that compares more than two objects and works on the command line:
The key part is the 'apply_expand' construct that takes a comparison function like 'isequal' and a cell array argument, and applies 'isequal' to the exanded cell array.
The example uses two versions of 'map', depending on if you want to supply multiple arguments via a cell array or as separate arguments. This then leads to having to use 'arrayfun' or 'cellfun' respectively.
%% Prepare three objects to be compared
objs = { table(rand(5)), table(rand(5)), table(rand(5)) };
% Selectors for the aspects to compare:
get_aspects_to_compare = { @size, @(T) T.Properties.VariableNames };
%% Helper functions
apply_expand = @(fcn, C) fcn(C{:}); % Example: apply_expand(@isequal, {1, 1, 1})
cellfun_c = @(varargin) cellfun (varargin{:}, 'UniformOutput', false);
arrayfun_c = @(varargin) arrayfun(varargin{:}, 'UniformOutput', false);
% Alt 1, example: map_1(get_aspects_to_compare, objs(1))
map_1 = @(fcns, values) cellfun_c(@(f) f(values{:}), fcns);
assert(apply_expand(@isequal, arrayfun_c(@(o) map_1(get_aspects_to_compare, o), objs)))
% Alt 2, example: map_1(get_aspects_to_compare, objs{1})
map_2 = @(fcns, varargin) cellfun_c(@(f) f(varargin{:}), fcns);
assert(apply_expand(@isequal, cellfun_c( @(o) map_2(get_aspects_to_compare, o), objs)))
  1 件のコメント
Christian Ridderström
Christian Ridderström 2021 年 8 月 13 日
In practice I'd use something like the above, but I'll accept Stephens answer in a while as:
a) It answered that I cannot do: assert(isequal(foo(result)))
b) I very much appreciated learning about being able to do: foo().something.



Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by