Is it possible to pass argument blocks between functions?
5 次查看(过去 30 天)
显示 更早的评论
Hello,
I was wondering if it is possible to reuse argument block of functions. Maybe the following example makes my idea more clear:
In a data class I have a filter method. This filter method has an argument block with multiple filter criteria:
function output = findTest(obj, filterlogic_in, options)
arguments
obj className
filterlogic_in {mustBeMember(filterlogic_in,{'and', 'or', 'not'})} = 'and'
options.filter1 (1,:) = nan
options.filter2 (1,:) {mustBeMember(options.filter2,{'', 'test1', 'test2'})} = {''} %Filter for test type
end
%here happens the filtering
end
In the class I also have multiple methods that do a filtering first if needed, e.g. calculate average data:
function output = calcAvg(obj, filterlogic_in, options)
arguments
obj className
filterlogic_in {mustBeMember(filterlogic_in,{'and', 'or', 'not'})} = 'and'
options.filter1 (1,:) = nan
options.filter2 (1,:) {mustBeMember(options.filter2,{'', 'test1', 'test2'})} = {''} %Filter for test type
end
%Use the findTest method
filteredData = obj.findTest(filterlogic_in, "filter1", options.filter1, "filter2", options.filter2)
%here starts the rest of the function to calculate the average
end
My question: Is it possible to 'pass' or 'inhert' the argument block from the findTest method to other methods. E.g. If I add a new filter, then I have to change the arguement block of all other methods using findTest.
Thanks a lot
2 个评论
Stephen23
2023-8-23
Why does CALCAVG to check the arguments for FINDTEST? Let each function determine its own input requirements, i.e. simply pass the inputs to FINDTEST, and let FINDTEST decide if they are okay or not.
回答(1 个)
Gagan
2023-9-4
Hi jr1995
Reusing the ‘arguments’ block in multiple functions is indeed possible. One approach is to create a dedicated function that handles argument validation using the ‘arguments’ block, and the other functions can invoke this function to validate the arguments. This way, the validation logic is centralized and can be reused across multiple functions.
For Example :-
function argumentsBlock(className, filterlogic_in, options)
arguments
className
filterlogic_in {mustBeMember(filterlogic_in,{'and', 'or', 'not'})} = 'and'
options.filter1 = nan
options.filter2{mustBeMember(options.filter2,{'', 'test1', 'test2'})} = {''}
end
end
function output = findTest()
options.filter1 = nan;
options.filter2 = "test1";
argumentsBlock("Hello",'and', "filter1", options.filter1, "filter2", options.filter2);
end
In the above code snippet,
Function named 'argumentBlock' is responsible for validating the arguments. And the function 'findTest' utilizes the 'argumentBlock' function to perform the necessary argument validation.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!