How to define dependent dimensions in argument validation block

25 visualizzazioni (ultimi 30 giorni)
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.

Risposta accettata

Aishwarya Shukla
Aishwarya Shukla il 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.
  1 Commento
Besmir
Besmir il 29 Mar 2023
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.

Accedi per commentare.

Più risposte (0)

Categorie

Scopri di più su Argument Definitions in Help Center e File Exchange

Prodotti


Release

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by