Function Argument Validation accepting "areyoukiddingme" as (1, 4) double

Very simple example:
function [] = testFunc(input)
arguments (Input)
input (1, 4) double
end
fprintf('class=%s, size=%s\n', class(input), mat2str(size(input)));
disp("Success!");
end
This results in the following:
>> testFunc(1)
class=double, size=[1 4]
Success!
>> testFunc(NaN)
class=double, size=[1 4]
Success!
>> testFunc("areyoukiddingme")
class=double, size=[1 4]
Success!
Now, ChatGPT insists that this is correct behaviour (which is a bit of a stretch) and by design - does this yield that the whole Function Argument Validation is rather useless, because there can always be some arbitrary, not or badly documented transformation moving any class to another class? Like it is a pretty big jump from "areyoukiddingme" to [NaN, NaN, NaN, NaN].

4 Comments

Like it is a pretty big jump from "areyoukiddingme" to [NaN, NaN, NaN, NaN].
The conversion actually produces a scalar NaN,
double("areyoukiddingme")
ans = NaN
It gets replicated into [NaN, NaN, NaN, NaN] because your (1, 4) validation spec causes the scalar value to be replicated into a 1x4 vector.
I suppose doing the busy work for the arguments block is probably not much more difficult/effort than prior practice--although I also still fail to see why it does such aggressive implicit conversion as the default behavior.
The one real advantage on comparison is one gets the warning/error on the specific failure mode by default with the arguments block whereas would have to test/report each condition this way.
function res=myfunc(x)
isrow(x)
assert(all(isfinite(x)) && numel(x)==4 && isrow(x), 'X must be row 4 vector')
res=sum(x);
end
x=1:4;
myfunc(x)
ans = logical
1
ans = 10
myfunc(x.')
ans = logical
0
Error using assert
X must be row 4 vector

Error in solution>myfunc (line 3)
assert(numel(x)==4 && isrow(x), 'X must be row 4 vector')
Matt J
Matt J on 18 Nov 2026 at 21:16
Edited: Matt J on 18 Nov 2026 at 21:27
I suppose doing the busy work for the arguments block is probably not much more difficult/effort than prior practice--although I also still fail to see why it does such aggressive implicit conversion as the default behavior.
Arguments blocks do not exist only for the purpose of throwing errors. They're also to replace all the preliminary shaping, explicit expansion, and type casting that can otherwise clutter up your code.
I've been placidly unawares of most of the facilities having blithely ignored them since their introduction. :>) Having now seen @Steven Lord's expansion, I see what I thought lived only inside the operators or assignments actually exists at a higher level.
As noted in that response, with that clarification, it could take some pretty serious study to really figure out what, specifically, should be constrained in the block to produce precisely the desired capabilities and only the desired capabilites depending upon just what the function purpose were to be.

Sign in to comment.

Answers (3)

Keep reading the documentation -- you have to add the <validation functions> to <prevent the automagic implicit conversion>.
function [] = testFunc(input)
arguments (Input)
input (1, 4) double {mustBeNumeric,mustBeReal,mustBeFinite}
end
fprintf('class=%s, size=%s\n', class(input), mat2str(size(input)));
disp("Success!");
end
try % put in try...catch block so can run both tests
testFunc(nan)
catch ME
fprintf('%s\n%s\n',ME.identifier,ME.message) % see what killed the first...
end
MATLAB:validators:mustBeFinite Invalid argument at position 1. Value must be finite.
testFunc('Areyoukidding?') % now can run second since didn't abort...
Error using solution>testFunc (line 4)
Invalid argument at position 1. Value must be a vector with 4 elements.
I've used argument validation very little because it does seem like it takes a lot of effort to make it actually work. I've wondered if there might not be a way to have a {noimplicitconversion} option to be able to shut some or all of this off, but I've not used enough nor thought about it in depth. But, the above kind of thing is a sizable part of why haven't adopted it as a routine practice, agree.

8 Comments

How strict would you expect the "no implicit conversion" option to be? If I had an argument that was restricted to being an int8 with implicit conversion disallowed, would you expect specifying the literal value 1 in the function call (not a variable with the value 1) to be an error? That literal is treated by MATLAB as a double rather than an int8, after all.
class(1)
ans = 'double'
As noted, I am very unfamiliar with the details of the argument block; prior to your prior amplification I had presumed that overloading/expansion occurred inside the operators internal to the function not on the argument list elements themselves. I stand corrected; would have to study this a whole lot more to begin to understand how one would write strictly conforming to expectations argument checking this way. In general, MATLAB coercion is helpful in that one can do arithmetic on char() variables, etc., that is handy in some cases.
To answer the speciric Q? posed would have to depend upon the actual function, I think, although in general one doesn't pay any attention to what specific class a numeric variable/value belongs to--but, if it were a value passed to a function expecting a bit feld for a hardware register, then it would likely need to be assured to be the integer type.
"If I had an argument that was restricted to being an int8 with implicit conversion disallowed, would you expect specifying the literal value 1 in the function call (not a variable with the value 1) to be an error?"
Correct.
If the user wanted int8 with implicit conversion allowed, then they would not specify that restriction.
As far as I can tell, the ARGUMENTS block approach is to use mustBeA(a,"uint8")
but, if it were a value passed to a function expecting a bit feld for a hardware register, then it would likely need to be assured to be the integer type.
The value 1 is a perfectly valid integer value. And if you'd included that class restriction in your arguments block, that integer value (whatever its numeric type coming in) would be stored as the integer type you listed in your restriction. That strikes me as what you'd want; you wouldn't want a double coming in to be stored as a double if you're going to be using it as a double. [This has been a matter of some discussion in the past with the bitwise functions like bitand, bitor, bitxor, etc.]
for types = {@double, @single, @int8, @uint16, @int32, @uint64}
one = types{1}(1);
fprintf("Before calling myfun, one is of class %s.", class(one))
myfun(one)
end
Before calling myfun, one is of class double.
x is int8 and has value 1.
Before calling myfun, one is of class single.
x is int8 and has value 1.
Before calling myfun, one is of class int8.
x is int8 and has value 1.
Before calling myfun, one is of class uint16.
x is int8 and has value 1.
Before calling myfun, one is of class int32.
x is int8 and has value 1.
Before calling myfun, one is of class uint64.
x is int8 and has value 1.
function myfun(x)
arguments
x (1, 1) int8;
end
fprintf("\tx is %s and has value %d.\n", class(x), x)
end
"The value 1 is a perfectly valid integer value"
MATLAB disagrees:
isinteger(1)
ans = logical
0
"The value 1 is a perfectly valid integer value" ... MATLAB disagrees:
isinteger() disagrees, but not Matlab as a whole,
try
mustBeInteger(1)
fprintf ('Value is integer')
catch
fprintf('Value is not integer')
end
Value is integer
try
mustBeInteger(pi)
fprintf ('Value is integer')
catch
fprintf('Value is not integer')
end
Value is not integer
@doc:isinteger checks if the argument is an integer type. The value of the argument is irrelevant.
@doc:mustBeInteger checks the value of the argument, not the type.
Note that myfun, as implemented, will cast non-integer values as well, so an actual implementation might need mustBeInteger as a validator.
myfun(1.2)
x is int8 and has value 1.
function myfun(x)
arguments
x (1, 1) int8;
end
fprintf("\tx is %s and has value %d.\n", class(x), x)
end
@Stephen23: isinteger checks type, not value. "TF = isinteger(A) returns logical 1 (true) if A is an array of integer type. Otherwise, it returns logical 0 (false)."
Yes, this is something that trips up a lot of people and has for a very long time, since the introduction of the function in 2004's release R14 IIRC. I don't remember off the top of my head the rationale for this distinction. I suspect it might have been related to making a function encapsulating the behavior of the isa function with numericCategory 'integer'. This could have been to make it more discoverable as part of the introduction of non-double arithmetic into MATLAB, which I believe also happened in release R14.
@Matt J: Yes, mustBeInteger checks value and doesn't care about type. "mustBeInteger(value) throws an error if value does not contain integer values. This function tests for numbers with no fractional part. The data type of the values is not considered. mustBeInteger does not return a value."

Sign in to comment.

Would you expect that in order to add two arrays together, they must be exactly the same size?
x = [1 2 3 4];
y = 5;
shouldThisWork = x + y
shouldThisWork = 1×4
6 7 8 9
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
If you were to look at the contents of that local variable input (I would strongly advise you to change that name, as there is a built-in function by that name in MATLAB) in each of your cases you'd see that the variable contains four copies of the scalar input value that you provided. This (and the behavior of + above) is the result of scalar expansion, a simple form of implicit expansion, that's been part of MATLAB probably since Cleve's original version. [Implicit expansion is newer, only several years old.]
testFunc(1)
1 1 1 1
testFunc(NaN)
NaN NaN NaN NaN
testFunc("areyoukiddingme")
NaN NaN NaN NaN
Yes, "areyoukiddingme" is a scalar string. The reason it becomes NaN is because "areyoukiddingme" is not a string form of a double. Compare:
testFunc("3.14159")
3.1416 3.1416 3.1416 3.1416
If you'd passed in the char vector 'areyoukiddingme' it wouldn't have worked, as that is a 1-by-15 char array.
try
testFunc('areyoukiddingme')
catch ME
fprintf("This threw error ""%s"".\n", ME.message)
end
This threw error "Invalid argument at position 1. Value must be a vector with 4 elements.".
It would have worked with a 1-by-4 char array, converting each character into its numerical code.
testFunc('pear')
112 101 97 114
The fact that function argument validation supports scalar expansion is described in the Validate Size and Class section of this documentation page: "MATLAB indexed assignment rules apply to size specifications. For example, a 1-by-1 value is compatible with the size specified as (5,3) because MATLAB applies scalar expansion. "
function [] = testFunc(input)
arguments (Input)
input (1, 4) double
end
disp(input)
end

8 Comments

I generally understand what you are saying. It still does not make any sense - functionally the Argument Validation treats any String, Scalar and (1x4)-double the same. Then what is the Function Argument Validation for?
It's a bit like a Bouncer, who is supposed to let only Adults into the Club, but of course the three 6-year olds can also enter, because 3 times 6 is 18.
"...what is the Function Argument Validation for?"
Without adding additional restrictions, it follows MATLAB's implicit conversion rules as you've written the base case; as <noted and illustrated in previous Answer>, you have to read the actual syntax of the feature to restrict that default behavior if that is the desired result.
Your validation structure is simply incorrectly written to produce the result you are wanting; that's incorrect use of the facility, not an error or shortcoming in the facility itself. As noted before, read the rest of the documentation on how the argument blocks actually work; to restrict some type casting, you need to define which and incorporate those with one or more of the validation functions.
Also note there's a difference in what MATLAB does with a string variable as compared to a char() string array--
double("Bouncer")
ans = NaN
double('Bouncer')
ans = 1×7
66 111 117 110 99 101 114
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
The string class treats the content as a single entitiy and, as noted previously, since it isn't a recognizable numeric field, it gets turned into a NaN.
OTOH, the char() string is internally an array of integers being interpreted as text by lookup into the ASCII table of the associated letter for each numeric value. Hence, internally they are just numbers and double() returns what that ASCII code is for each as an array of double.
Another illustration--
'A'+1
ans = 66
char(ans)
ans = 'B'
But,
"A"+1
ans = "A1"
for the string class, the plus, + operator is overloaded to be string catenation, not arithmetic.
Can you share any insight into the decision to make explicit scalar expansion the default behavior for the Arguments block, with the concommitant increase in memory footprint?
I'm trying to think of a situation where a scalar must be expanded into a matrix because the scalar can't be used directly.
I'm trying to think of a situation where a scalar must be expanded into a matrix because the scalar can't be used directly.
A typical instance where it can't be used directly is when the code indexes that input variable, believing that it is a matrix or vector. If the variable were stored as an unreplicated scalar, you would get index out of range errors.
It's a bit like a Bouncer, who is supposed to let only Adults into the Club, but of course the three 6-year olds can also enter, because 3 times 6 is 18.
A more straightforward example is vending machines. Some vending machines will accept two dimes and a nickel for something costing 25 cents. It cares about the value not the form factor / "type", asking "is the input 'convertible to' a quarter?" (or convertible to 25 cents of money.) For this you'd probably want something along the lines of:
payment Currency {mustBeWorth25Cents}
where the input could be a Quarter object, a vector of [Dime Dime Nickel] objects, etc. and the local validator function mustBeWorth25Cents makes sure it's at least 25 cents in value. [I haven't designed the money object hierarchy so this is 'air code', an on-the-fly mock-up for demonstration purposes. Currency could be a superclass of a heterogeneous hierarchy with subclasses Nickel, Dime, Quarter, and a general Cents class.]
Others, like a gumball machine, require an actual quarter because that's what fits in the slot. That cares about the form factor / "type"; two dimes and a nickel won't work. Something like:
payment (1, 1) Quarter {mustBeA(payment, "Quarter")}
which would be strict that the input must be an instance of Quarter not just a Quarter's worth of value / something convertible to a Quarter.
Can you share any insight into the decision to make explicit scalar expansion the default behavior for the Arguments block, with the concommitant increase in memory footprint?
After the Arguments block finishes, if you asked for a variable that you size validated to say (1, 4), calling size on that variable better return [1 4]. Returning something else would be surprising. You could even assert that the variable has size [1 4].
x(1:4) = 1;
assert(isequal(size(x), [1 4]))
If that assert failed, I'd be extremely suspicious of what's going on in that code. [If x already existed, then yes that assert could fail if x had been larger before the first line. But that doesn't apply for an Arguments block.]
Compare what happens if the input is a vector. First let's look at the expected sized vector:
y = [1 2 3 4];
y(1:4) = y;
assert(isequal(size(y), [1 4])) % Works
Now one that's larger.
z = [1 2 3 4 5];
z(1:4) = z; % Whoops!
Unable to perform assignment because the left and right sides have a different number of elements.
assert(isequal(size(z), [1 4])) % Never reached; the previous line threw an error first
You might say "But the only value stored in x is 1, couldn't you have the variable somehow "remember" that its size is [1 4] and all the elements are equal to 1?" Sure. But that wouldn't be a plain old double. The closest equivalent in MATLAB is probably sparse, which doesn't store elements in the matrix that are 0. And sometimes that different storage scheme (compared to full) requires significantly different implementations between sparse and full. See the flowcharts on the mldivide documentation page as one example. So likely it would be more complicated to work with.
If I'm understanding your comment, I was actually thinking the other way.
If the Arguments block is
%{
arguments
z (4, 4) ;
end
%}
then why isn't that treated as an assertion that, on input, x must be 4x4 and error if it isn't? I know it doesn't work that way, but I'm trying to understand why it doesn't.
I mean if the main body of the function requires that z be a 4x4 matrix, I'm trying to think of a case where such a function would want a scalar input explicitly expanded to a 4x4 matrix. It seems like that scalar expansion is primarily for convenience so that it doesn't need to be done at the call site. Though I do agree the expansion would have to be done somewhere, so my comment about memory footprint doesn't apply.
I'm trying to think of a case where such a function would want a scalar input explicitly expanded ...
Think of the commands ones(), zeros(), nan(), inf() etc.. All of these expand scalar input to form a 1x2 vector. For example, ones(n) is equivalent to ones([n,n]).
Alternatively, suppose you are writing a function that composes a DICOM image file. One of the inputs might be the image pixel dimensions in millimeters for the DICOM metadata. The arguments block entry might look like this:
arguments
pixelSize (1,2) single;
end
In the generic case, when the pixels are rectangular, you would input the dimensions as a pair [height,width] but if the pixels are square, which is a common case, it is convenient to input a scalar, to be used for both height and width.
If the Arguments block is
arguments
z (4, 4) ;
end
why isn't that treated as an assertion that, on input, x must be 4x4 and error if it isn't?
Because that's not what that syntax is meant for. If you want an assertion like that, the supported way would be to create an appropriate validation function, e.g.,
function mustHaveDims(A, dims)
if ~isequal(size(A), dims)
error('mustHaveDims:InvalidSize', ...
'Expected size %s, received %s.', ...
mat2str(dims), mat2str(size(A)));
end
end
whereupon you could have arguments blocks like,
function myFunction(x)
arguments
x {mustHaveDims(x, [4, 4])}
end
end

Sign in to comment.

does this yield that the whole Function Argument Validation is rather useless
Function argument validation is not useless, but you have not included any argument validators in your code. To put a finer point on it, you are taking liberties with the terminology "function argument validation". The parameters circled in red below are NOT for argument validation. Those are conversion parameters (but see Footnote).
Argument validators are the things that appear in braces (mustBeInteger, mustBeNumeric, etc...), which you currently do not have. To perform the argument validation you appear to be attempting, you would do,
function [] = testFunc(input)
arguments (Input)
input {mustBeNumeric, mustBeA(input,"double"), mustHaveDims(input,[1,4])}
end
fprintf('class=%s, size=%s\n', class(input), mat2str(size(input)));
disp("Success!");
end
function mustHaveDims(A, dims)
if ~isequal(size(A), dims)
error('mustHaveDims:InvalidSize', ...
'Expected size %s, received %s.', ...
mat2str(dims), mat2str(size(A)));
end
end
Footnote: Conversion specifiers can provide a kind of indirect validation in the sense that, if the conversion fails, an error is thrown. But they are not intended as a way of affirmatively asserting characteristics that you want the input to have.

Products

Release

R2026a

Asked:

on 18 Nov 2026 at 16:56

Edited:

21 minutes ago

Community Treasure Hunt

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

Start Hunting!