필터 지우기
필터 지우기

arguments block seems wrong

조회 수: 5 (최근 30일)
Duijnhouwer
Duijnhouwer 2020년 8월 21일
댓글: Walter Roberson 2020년 8월 22일
the arguments block can be used to validate input arguments. Great! Except that it doesn't seem to work as advertised.
According to the documentation (doc arguments)
"The value assigned to the argument in the function call must be compatible with the specified size, or MATLAB throws an error."
However, when calling this function
function a=f(a)
arguments
a (1,3) double
end
end
with a scalar
>> f(1)
ans =
1 1 1
The function expands the erroneous scalar argument to a 3-element vector instead of casting the error that was promised!
Why would this be? Am I reading it wrong?
  댓글 수: 1
Duijnhouwer
Duijnhouwer 2020년 8월 21일
편집: Duijnhouwer 2020년 8월 21일
>> disp(version)
9.8.0.1417392 (R2020a) Update 4

댓글을 달려면 로그인하십시오.

답변 (1개)

Walter Roberson
Walter Roberson 2020년 8월 21일
Documented. The size of the input must be "compatible" taking into account implicit expansion.
https://www.mathworks.com/help/matlab/matlab_prog/function-argument-validation-1.html#mw_48fe4f61-8ee4-424b-ae2b-c82b8d051910
  댓글 수: 5
Bruno Luong
Bruno Luong 2020년 8월 22일
Only scalar expansion is tolerated by ARGUMENTS, which exists in MATLAB well before R2016b
function a=f(a)
arguments
a (5,3) double
end
end
I don't know what Walter meant by implicit expansion, but the singleton expansion is not tolerated.
>> f(rand(5,3))
ans =
0.6229 0.9431 0.6980
0.2473 0.5422 0.9468
0.9195 0.5459 0.2302
0.0582 0.1777 0.2003
0.9456 0.8473 0.7904
>> f(rand(1))
ans =
0.0317 0.0317 0.0317
0.0317 0.0317 0.0317
0.0317 0.0317 0.0317
0.0317 0.0317 0.0317
0.0317 0.0317 0.0317
>> f(rand(5,1))
Error using f
Invalid argument at position 1. Value must be a matrix of size 5-by-3.
>> f(rand(1,3))
Error using f
Invalid argument at position 1. Value must be a matrix of size 5-by-3.
>>
Walter Roberson
Walter Roberson 2020년 8월 22일
Ah, this part seems to be the key:
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. Also, MATLAB row-column conversion applies so that a size specified as (1,:) can accept a size of 1-by-n and n-by-1.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by