Setup
Let's say I have some function that a number of arrays as an input and does something with them that requires the arrays to have compatible sizes (i.e., to have the same sizes after implicit singleton dimension expansion). I have written a function mustBeCompatibleSize
that throws an error if it's arguments have incompatible sizes. This works as expected. It correctly points out which argument is causing the error to the user.
function multiArrayOperation1(Array1, Array2, Array3)
arguments
Array1;
Array2 {mustBeCompatibleSize(Array1, Array2)};
Array3 {mustBeCompatibleSize(Array1, Array2, Array3)};
end
% Do something with Array1, Array2, and Array3.
end
For example, calling multiArrayOperation1(ones(5, 1), ones(1, 5), ones(5, 6))
will result in MATLAB telling the user that the 3rd argument was not compatible with previous arguments.
Issue
The issue comes about when I want to make a function that accepts any number of input arrays, using the (Repeating) arguments block, like in the example below. This example does not work, as the argument validator passes only one element at a time into the mustBeCompatibleSize
function, and thus no error is thrown.
function multiArrayOperation2(Arrays)
arguments (Repeating)
Arrays {mustBeCompatibleSize};
end
% Do something with Arrays.
end
For example, calling multiArrayOperation2(ones(5, 1), ones(1, 5), ones(5, 6))
does not result in an error being thrown.
Nonoptimal Solution
Of course, we can just call the validation function manually after the arguments block. However, this does not display to the user which argument is causing the error as it does in the first example, and doesn't really utilize the arguments block for validation.
function multiArrayOperation3(Arrays)
arguments (Repeating)
Arrays;
end
mustBeCompatibleSize(Arrays{:});
% Do something with Arrays.
end
For example, calling multiArrayOperation3(ones(5, 1), ones(1, 5), ones(5, 6))
throws an error as it should, but the user is not informed which specific argument is causing the error.
Question
Is there a better solution to this issue? Hopefully, there is a way to implement something similar to the second example.