필터 지우기
필터 지우기

How to make user-defined type pass as numeric?

조회 수: 1 (최근 30일)
Naor Movshovitz
Naor Movshovitz 2015년 10월 10일
댓글: Geoff Hayes 2015년 10월 10일
Suppose I have a defined type that behaves like a number. I would like it to pass the test:
validateattributes(x, {'numeric'}, {})
It's not enough, apparently, to overload the function isnumeric.m. What else needs to be done?
Thanks, n

채택된 답변

Geoff Hayes
Geoff Hayes 2015년 10월 10일
편집: Geoff Hayes 2015년 10월 10일
Naor - try overloading the isa function instead. For example, let's suppose that the following class is "numeric".
classdef MyNumberClass
properties
x
end
methods
function obj = MyNumberClass(varargin)
if nargin > 0
obj.x = 42;
else
obj.x = 99;
end
end
function [result] = isa(obj,typeStr)
result = false;
if strcmpi(typeStr,'numeric') || strcmpi(typestr,'MyNumberClass')
result = true;
end
end
end
end
Then in the Command Window, try the following
myInstance = MyNumberClass;
Now try to validate it as
validateattributes(myInstance, {'numeric'}, {})
No error is thrown and so the object is considered to be numeric. Note that you would need to overload isnumeric so that that function "passes" too.
  댓글 수: 2
Naor Movshovitz
Naor Movshovitz 2015년 10월 10일
Thanks Geoff,
This does what I wanted so I accepted the answer. If you can, please edit your answer to make the overloaded isa() method return true also on type MyNumberClass.
One tiny corner that is not really that important but would be nice to know how to fix is the error message generated when validateattributes fails:
validateattributes('s',{'numeric'},{})
Expected input to be one of these types:
double, single, uint8, uint16, uint32, uint64, int8, int16, int32, int64
Instead its type was char.
It would be nice if the message mentioned MyNumberClass at the end.
Geoff Hayes
Geoff Hayes 2015년 10월 10일
Naor - I've updated the solution with your suggestion. As for including your class in the error output, I'm not sure how that can be done.

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Data Type Identification에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by