MATLAB Answers

Wrapper Function to call function with different number of input and ouput arguments

4 views (last 30 days)
Fabian Helde
Fabian Helde on 1 May 2020
Edited: Adam Danz on 1 May 2020
I am trying to design a wrapper function that takes a function-handle as input as well as a Struct that contains the function's arguments and a reference struct, that contains the desired number of outputs for the function and the fiedldnames, that they should be stored under in a return struct. Something like this:
Is there any way to "resolve" the Struct-Fields of InputData and use them as input-arguments for funcHandle, when the number of fields/input arguments may vary?
Thank you!
function TestStruct = callFunctionUnderTest(funcHandle, InputData, OutputData)
% InputData could be something like this:
% InputData.funcarg1
% InputData.funcarg2
% but with variable number of input arguments/fields!
% OutputData could be something like this:
% OutputData.output1
% OutputData.output2
% OutputData.output3
% but with variable number of outputs/fields!
TestStruct = [];
% check if number of fields in OutputData is equivalent to returned outputs of function
if nargout(funcHandle) ~= length(fieldnames(OutputData))
error
end
% function call
[TestStruct.(ouput1), TestStruct.(output2), TestStruct.(output3)] = funcHandle(InputData.funcarg1, InputData.funcarg2)
end

  0 Comments

Sign in to comment.

Accepted Answer

Adam Danz
Adam Danz on 1 May 2020
Edited: Adam Danz on 1 May 2020
For the inputs....
Convert the structure to a cell array using C = struct2cell(S)
Then,
funcHandle(InputData.funcarg1, c{:})
The order of the fields in S must be in order of input aguments.
For the outputs...
I don't quite understand what OutputData is or how it's used but if it somehow specifies the number of outputs,
out = cell(1,n); %where n is the expected number of outputs
[out{:}] = funcHandle(. . .)
If you want the output to be a structure instead of a cell array, see cell2struct().

  0 Comments

Sign in to comment.

More Answers (0)


Translated by