MATLAB Answers

Can Matlab's arguments function handle structs

20 views (last 30 days)
Clownfish
Clownfish on 25 Apr 2020
Commented: Marc Youcef on 29 Sep 2020
Hi,
I was wondering if it is possible to do argument validation with Matlab's arguments function like in the following example
function foo(Struct)
arguments
Struct.A double = 1
Struct.B double = 2
Struct.C char = 'hello
end
...
end

  0 Comments

Sign in to comment.

Answers (1)

Sriram Tadavarty
Sriram Tadavarty on 25 Apr 2020
Hi Clownfish,
Yes, the way you placed is possible and can be done through arguments.
Provided you need to input the structure as name value pairs to the function rather than structure itself. Look at the Name-Value pair section here.
For the script you have provided, you can do slight modifications to check if it works, as shown below:
function [a,b,c] = foo(Struct)
arguments
Struct.A double = 1
Struct.B double = 2
Struct.C char = 'hello'
end
a = Struct.A;
b = Struct.B;
c = Struct.C;
end
>> foo % outputs 1
>> [a,b,c] = foo % Outputs a with value 1, b with value 2 ,and c with value 'hello'
>> [a,b,c] = foo("A",100,"B",25,"C","Arguments") % Outputs a with 100, b with 25, and c with 'Arguments'
Hope this helps.
Regards,
Sriram

  3 Comments

Robert
Robert on 10 Jul 2020
Using an actual struct as input (like the poster asked) does not work though:
>> [a,b,c] = foo(struct("A",100,"B",25,"C","Arguments"))
Error using foo
Invalid argument list. Check for wrong number of positional arguments or placement of positional arguments after name-value pairs. Also, check for name-value pairs with invalid names or not specified in pairs.
does not work though. Is it possible to do this without defining custom validation, just like what is possible for the inputParser?
Matt J
Matt J on 10 Jul 2020
It's probably a recent upgrade. In R2020a, it does work:
K>> [a,b,c] = foo("A",100,"B",25,"C","Arguments")
a =
100
b =
25
c =
'Arguments'
Marc Youcef
Marc Youcef on 29 Sep 2020
You are still not passing in a struct as Robert mentions but Name, Value Pairs.

Sign in to comment.

Products


Release

R2019b

Community Treasure Hunt

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

Start Hunting!