Simple Explanation for ‘parse’
How to use the "parse" function to create optional function inputs
is there any way to parse the matlab code ?
How to parse text data
Hello, I’m really struggling with what parse actually does, and I’m finding the matlab documentation quite difficult to understand. I get what an input parser is, but I’m really struggling with what parse does in relation to that.
Thank you I’m advance!
You can use MATLAB's inputParser class:
http://www.mathworks.com/help/matlab/ref/inputparser-class.html http://blogs.mathworks.com/community/2012/02/13/parsing-inputs/
EDIT: I guess I'll just put the code in as well...
function y = f(x, extraOpts)
p = inputParser;
p.addRequired('x', @(x) length(x)>1);
p.addOptional('visualize', 1, @isscalar);
p.addOptional('N', 100, @isscalar);
p.parse(x, extraOpts{:});
do_things(x, extraOpts);
end
You might need to store the results of the parse, perhaps something along the lines of:
inputs = p.parse(x, extraOpts{:});
do_things(inputs)
END EDIT
Alternatively, you could do something like redefine your function to take the number of values in your struct though it's not as powerful as the input parser solution:
function y = f(N, visualize)
if nargin < 2
visualize = 0
end
if nargin < 1
visualize = 0
N = 100
end
I couldn't make the answer work, but I found another solution with inputParser, let me paste here for future reference :
function y = f2(extraOpts)
p = inputParser;
p.addParamValue('par1', 'defaultValue1');
p.addParamValue('par2', def2, @isnumeric);
p.addParamValue('par3', def3, @isnumeric);
p.parse(extraOpts{:});
extraOpts = p.Results;
end
the drawback is that I needed to separate the two inputs x and extraOpts and had to call f2 as a subroutine, defined in the same file as f. Maybe there is a more elegant way for this (i.e. one that does not require another function), but the example I have seen was also doing like that, and since it works, it's good for me :)