필터 지우기
필터 지우기

Single struct as alternative to name-value pairs in user-defined function

조회 수: 6 (최근 30일)
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

채택된 답변

Matt J
Matt J 2024년 7월 9일
편집: Matt J 2024년 7월 9일
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))
s1 = struct with fields:
a: 1 b: 2 c: 30
s2 = struct with fields:
x: 3 y: 4 z: 60
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
Jake
Jake 2024년 7월 9일
Thanks Matt, that's really helpful. I feared I might have to fall back to inputParser and was intimidated by the amount of code I thought might be required, but yours is a nice, concise solution. It's a shame there's no way to achieve the same effect with argument blocks, however
Matt J
Matt J 2024년 7월 9일
Yes, I agree. It's been suggested to TMW before, but I guess there are problems with the idea that we're not seeing.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

제품


릴리스

R2023a

Community Treasure Hunt

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

Start Hunting!

Translated by