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

5 次查看(过去 30 天)
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

采纳的回答

Adam Danz
Adam Danz 2020-5-1
编辑:Adam Danz 2020-5-1
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 个)

类别

Help CenterFile Exchange 中查找有关 Whos 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by