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

15 Ansichten (letzte 30 Tage)
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:
assert(isequal(foo(result)))
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{:});
end
If I can only do the latter, any suggestions for the name of 'bar'?
  2 Kommentare
J. Alex Lee
J. Alex Lee am 12 Aug. 2021
Bearbeitet: J. Alex Lee am 12 Aug. 2021
is there a reason not mentioned here that you must use this cell array route, rather than a strategy such as
function assertPairwisePropertyEquality(A,B,PropName)
PropA = A.Properties.(PropName);
PropB = B.Properties.(PropName);
assert(isequal(PropA,PropB))
end
Or maybe
propFcn = @(obj)(obj.Properties.VariableNames);
% propFcn = @(obj)(height(obj));
function assertPairwisePropertyEquality(A,B,fcn)
PropA = fcn(A);
PropB = fcn(B);
assert(isequal(PropA,PropB))
end
Christian Ridderström
Christian Ridderström am 13 Aug. 2021
Bearbeitet: Christian Ridderström am 13 Aug. 2021
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
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.

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

Stephen23
Stephen23 am 12 Aug. 2021
Bearbeitet: Stephen23 am 12 Aug. 2021
The closest is to use the new syntax which allows dot indexing directly into function outputs:
For example:
fprintf('%d\n',testfun().X)
123 456 789
function S = testfun()
S(1).X = 123;
S(2).X = 456;
S(3).X = 789;
end
Otherwise the reason why your approach will not work is already explained in detail in this comment (and thread):
  5 Kommentare
Christian Ridderström
Christian Ridderström am 14 Aug. 2021
See the answer below from @J. Alex Lee and also my comment where I create a helper function 'cellfun_s'.
Inspired by that answer, it allows doing e.g. the following - what to call things is the unclear part, hence it's 'foo' for now:
% Define helper function
foo = @(C) cell2struct(C, 'expand_as_list');
% Place some dummy results in a cell array
result_as_cell_array = {rand(1) < 0.5, rand(1) < 0.5}
result_as_cell_array = 1×2 cell array
{[1]} {[0]}
% Use 'foo(<x>).expand_as_list' to pass the expanded cell array as arguments to 'isequal'
isequal(foo(result_as_cell_array).expand_as_list)
ans = logical
0

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (2)

J. Alex Lee
J. Alex Lee am 13 Aug. 2021
Bearbeitet: J. Alex Lee am 13 Aug. 2021
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 calls...it 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 Kommentare
Christian Ridderström
Christian Ridderström am 14 Aug. 2021
Bearbeitet: Christian Ridderström am 14 Aug. 2021
Personally I think it's a annoying flaw in MATLAB that you can't brace-index into the temporary result. However, I suspect it's non-trivial for Mathworks to fix this, otherwise I think they'd done it already.
I'll have to look into your suggestion of going via a struct, that might be useful but I can't wrap my head around it yet.
Note: In Octave it works just fine to brace-index (I just checked it in https://octave-online.net/ ):
octave:1> foo = @(x) { x+1, x+2}; foo(5), foo(5){2}
ans =
{
[1,1] = 6
[1,2] = 7
}
ans = 7
Christian Ridderström
Christian Ridderström am 14 Aug. 2021
Bearbeitet: Christian Ridderström am 14 Aug. 2021
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
1
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
assert(all(comparison_results))

Melden Sie sich an, um zu kommentieren.


Christian Ridderström
Christian Ridderström am 13 Aug. 2021
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 Kommentar
Christian Ridderström
Christian Ridderström am 13 Aug. 2021
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.

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by