How can I use a variable number of structure fields as function arguments?
Show older comments
Hello,
I have a structure that conatins a function handle and any number of other variables (in this case 4), like so:
MyStruct = struct('MyFun',@example,'a',1,'b',2,'c',5,'d',37);
where example is a simple function that takes in a variable number of arguments and displays them, like so:
function [] = example(varargin)
for n = 1:2:length(varargin)
disp(['Argument ' varargin{n} ' = ' num2str(varargin{n+1})])
end
I would like to call the function handle (in this case @example) using the variables stored in MyStruct, like so:
>> X = fieldnames(MyStruct)
X =
5×1 cell array
{'MyFun'}
{'a' }
{'b' }
{'c' }
{'d' }
>> MyStruct.MyFun(X{2}, MyStruct.(X{2}), X{3}, MyStruct.(X{3}), X{4}, MyStruct.(X{4}), X{5}, MyStruct.(X{5}))
Argument a = 1
Argument b = 2
Argument c = 5
Argument d = 37
Is there a way to do this for a structure with any number of fields/variables?
[Note: the function handle can point to one of several functions]
For example:
>> MyStruct.MyFun(X{2}, MyStruct.(X{2}), X{3}, MyStruct.(X{3}), . . . , X{999}, MyStruct.(X{999}))
Any help at all would be greatly appreciated!
Thanks!
Accepted Answer
More Answers (1)
Bill Tubbs
on 5 Apr 2023
Edited: Bill Tubbs
on 5 Apr 2023
>> MyParams = struct('a',1,'b',2,'c',5,'d',37);
>> MyStruct = struct('Fun',@example,'Params',MyParams);
>> params = namedargs2cell(MyStruct.Params);
>> MyStruct.Fun(params{:})
1 Comment
Matt Flood
on 5 Apr 2023
Categories
Find more on Function Handles in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!