Created
August 21, 2017 11:53
-
-
Save alvaromartmart/8eb0d7d8f0130e7d4fa079db076b36b8 to your computer and use it in GitHub Desktop.
Matlab function signatures example for custom handle classes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
classdef foo < handle | |
properties | |
name = ''; | |
values = {}; | |
end | |
methods | |
function obj = foo(name,varargin) | |
% FOO returns a foo object | |
% foo('myFooObject'); % foo object with empty "values" | |
% foo('myFooObject',{1,2,'a','bbbb'}; % foo with initialized "values" | |
% foo('myFooObject',[],'random',true); % foo with random "values" | |
obj.name = name; | |
inputs = parseInputs(varargin); | |
if inputs.random | |
for i=1:10 | |
if(rand(1)>0.5) | |
obj.values = cat(2,obj.values,char(randi([0 100],1,8))); | |
else | |
obj.values = cat(2,obj.values,randi([0 100],1)); | |
end | |
end | |
else | |
obj.values = inputs.values; | |
end | |
function cfg = parseInputs(args) | |
p = inputParser; | |
% Define optional parameters | |
addOptional(p,'values',{},@iscell); | |
addParameter(p,'random',false,@islogical); | |
% Parse and return "cfg" struct | |
parse(p,args{:}); | |
cfg = p.Results; | |
end | |
end | |
function output = bar(obj,varargin) | |
% bar returns the "values" property of foo | |
% foo.bar(); % Returns all of "values" | |
% foo.bar('numbers') % Returns only numeric values in "values" | |
% foo.bar('strings') % Returns only char values in "values" | |
if nargin>1 | |
if strcmp(varargin,{'numbers'}) | |
isnumeric(obj.values) | |
output = obj.values(cellfun(@isnumeric,obj.values)); | |
elseif strcmp(varargin,{'strings'}) | |
output = obj.values(cellfun(@ischar,obj.values)); | |
else | |
error('Invalid flag'); | |
end | |
else | |
output = obj.values; | |
end | |
end | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"foo": | |
{ | |
"inputs":[ | |
{"name":"values","kind":"positional","type":["cell"]}, | |
{"name":"random","kind":"namevalue","type":["logical"]} | |
] | |
}, | |
"foo.bar": | |
{ | |
"inputs":[ | |
{"name":"obj","kind":"required","type":"foo"}, | |
{"name":"filter","kind":"flag","type":"choices={'numbers','strings'}"} | |
] | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment