How to define dependent dimensions in argument validation block
21 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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.
0 commentaires
Réponse acceptée
Aishwarya Shukla
le 29 Mar 2023
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.
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Argument Definitions dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!