Single struct as alternative to name-value pairs in user-defined function
2 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Hello, is it possible when defining a function with name-value argument pairs to allow a user to pass the struct(s) that define these name-value pairs directly to the function?
For example, I can define
function [s1, s2] = TestStructArgs(s1, s2)
arguments
s1 (1,1) struct
s2 (1,1) struct
end
end
then call TestStructArgs(struct('a', 1, 'b', 2), struct('x', 3, 'y', 4))
Or, I can define
function [s1, s2] = TestStructArgs2(s1, s2)
arguments
s1.a (1,1) double
s1.b (1,1) double
s2.x (1,1) double
s2.y (1,1) double
end
end
and call TestStructArgs2('a', 1, 'b', 2, 'x', 3, 'y', 4)
But what if I would also like to call the second example by passing whole structs, TestStructArgs2(struct('a', 1, 'b', 2), struct('x', 3, 'y', 4)) ? There doesn't appear to be any ambiguity in allowing both approaches, if they're not mixed-and-matched.
Further, some MATLAB built-in functions permit this e.g. the following runs just fine
>> opts = struct('Color', 'r', 'LineWidth', 2);
>> x = linspace(0,1,200); y = cos(x);
>> plot(x, y, opts)
There is an answer on the messageboard from 2022 here which suggests adding the attribute StructExpand after arguments but this causes an error if I add it to the above example
Many thanks for any help
0 commentaires
Réponse acceptée
Matt J
le 9 Juil 2024
Modifié(e) : Matt J
le 9 Juil 2024
You would have to use the older inputParser system to do that kind of thing, with the StructExpand property set to true (the default), e.g.,
TestStructArgs2(struct('a', 1,'b',2), struct('x', 3, 'y', 4))
function TestStructArgs2(varargin)
p=inputParser;
addParameter(p,'a',10,@isscalar);
addParameter(p,'b',20,@isscalar);
addParameter(p,'c',30,@isscalar);
addParameter(p,'x',40,@isscalar);
addParameter(p,'y',50,@isscalar);
addParameter(p,'z',60,@isscalar);
parse(p,varargin{:});
p=p.Results;
s1=struct('a',p.a,'b',p.b,'c',p.c)
s2=struct('x',p.x,'y',p.y,'z',p.z)
end
2 commentaires
Matt J
le 9 Juil 2024
Yes, I agree. It's been suggested to TMW before, but I guess there are problems with the idea that we're not seeing.
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Structures dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!