Check if input is a 4 element vector

조회 수: 7 (최근 30일)
OblongPea
OblongPea 2019년 12월 11일
댓글: Stephen23 2019년 12월 12일
I'm trying to write an error check in a function code, which should check if the input is specifically a 4-element vector.
All i have so far is:
if ~isvector(x)
error('Inputs must be vector')
end
Is there a way to write a code in order to check if the input, x, is a 4-element (row) vector.?
I'd like it to throw an error if the input x is for example a 2-element row vector, and of course if it is not a vector.
Thanks

채택된 답변

Guillaume
Guillaume 2019년 12월 11일
편집: Guillaume 2019년 12월 11일
The simplest way to do this kind of checks is to use validateattributes which will give you consistent comprehensive and localised error messages and check for a lot more properties. In your case,
validateattributes(x, {'numeric'}, {'row', 'numel', 4});
%or
validateattributes(x, {'numeric'}, {'row', 'numel', 4}, mfilename, 'x'); %for an even better error message
You may want to add 'finite' to the list of required attributes.
  댓글 수: 2
OblongPea
OblongPea 2019년 12월 12일
Many thanks, this also works!
Guillaume
Guillaume 2019년 12월 12일
Not only does it work, but as I explained, it's way better than the answer you've accepted. It will generate the same kind of error message that matlab issues, so the user is familiar with the format, the error message will be in the language that the user uses as well, and it's trivial to add more properties to check, properties that you probably haven't even thought to check, e.g. does your code work with NaN or Inf? sparse vectors? complex vectors? If not, it's trivial to add to the list of attributes:
validateattributes(x, {'numeric'}, {'row', 'numel', 4, 'finite', 'real', 'nonsparse'}, mfilename, 'x'); %for an even better error message
and it makes it also a lot easier to understand what properties are required since they're spelled out in words.

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

추가 답변 (1개)

Turlough Hughes
Turlough Hughes 2019년 12월 11일
편집: Turlough Hughes 2019년 12월 11일
if size(x,2)~=4 || ~isvector(x) || ~isnumeric(x)
error('Input must be a row vector of length 4')
end
  댓글 수: 3
OblongPea
OblongPea 2019년 12월 12일
Thanks, this now works a treat!
Stephen23
Stephen23 2019년 12월 12일
Simpler to use assert:
assert(isnumeric(x) && isrow(x) && numel(x)==4, 'Input must be a row vector of length 4')

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

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

제품


릴리스

R2017a

Community Treasure Hunt

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

Start Hunting!

Translated by