How to define dependent dimensions in argument validation block

22 次查看(过去 30 天)
I'm writing a function that processes a matrix to which I'd like the to add an option name-value arguments.
The size of the optional argument needs to be the width or length of the InputMatrix to avoid errors and I'd like to keep do as much input validation as possible inside the arguments block.
Example Code
function [out] = somefun(InputMatrix, options)
arguments
InputMatrix (:,:) % size NxN where N!=0
option.ColumnNames (1, width(InputMatrix)) {mustBeText} % <- width argument not supported here
end
out = []
end
In this example I'd like to add some columnnames to the vector, for example for plotting. This needs to be the same size as the matrix.
If possible I'd like to avoid validating the size inside the function because it's easier to maintain inside of the arguments block.
Does anyone know of a way to force "arguments " to accept a variable or an clean alternative.

采纳的回答

Aishwarya Shukla
Aishwarya Shukla 2023-3-29
One approach to validate the size of the ColumnNames option is to use a custom validation function. This validation function can take both the InputMatrix and the ColumnNames option as inputs and check whether the size of the ColumnNames matches the width of the InputMatrix. Here's an example implementation:
function [out] = somefun(InputMatrix, options)
arguments
InputMatrix (:,:) % size NxN where N!=0
option.ColumnNames {validateColumnNames(InputMatrix,option.ColumnNames)} % validate using custom function
end
% rest of the function
out = [];
end
function validateColumnNames(InputMatrix, ColumnNames)
% custom validation function to check size of ColumnNames
if ~isempty(ColumnNames) && size(ColumnNames, 2) ~= size(InputMatrix, 2)
error('ColumnNames must have the same width as the input matrix.')
end
end
In this implementation, the ColumnNames option is validated using the validateColumnNames function which takes both the InputMatrix and ColumnNames as inputs. This function checks whether the size of the ColumnNames matches the width of the InputMatrix. If it doesn't, an error is thrown.
Note that the validateColumnNames function is defined within the same file as the somefun function, which makes it accessible only within that file. If you need to use the same validation function across multiple files, you can define it in a separate file and add it to the MATLAB path.
  1 个评论
Besmir
Besmir 2023-3-29
ah neat! thanks.
That's a pretty nice way to do custom validation. I didn't think that you could just throw in a function.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Argument Definitions 的更多信息

产品


版本

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by