Why do I receive the error "<operation> not defined for variables of class <class>" in MATLAB?

3 views (last 30 days)
Why do I receive the error "<operation> not defined for variables of class <class>" in MATLAB?
If I try to operate on an array that contains variables of a type other than double, I receive an error of that general form. For example:
A=uint8(7);
sqrt(A)
gives me the error message:
ERROR: ??? Error using ==> -
Function 'sqrt' not defined for variables of class 'uint8'.

Accepted Answer

MathWorks Support Team
MathWorks Support Team on 14 Oct 2022
Edited: MathWorks Support Team on 10 Nov 2022
Most mathematical operators in MATLAB are only defined for variables of class double. To determine which functions can operate on different data types, such as uint8, please see:
You can also look at the help for the data type in question.
There are three ways you can avoid this problem, if you need to perform mathematics on operators of a different type. The first method is to convert or cast them to a double using the DOUBLE function, perform normal double precision operations on them, then convert them back to their original class.
The second method, if you have the Image Processing Toolbox version 3.0 or later, is to use the IMADD, IMSUBTRACT, IMMULTIPLY, or IMDIVIDE functions. These functions will perform arithmetic on arrays regardless of data type, as long as the types are consistent.
The third method, which is especially useful if you will be performing the operations repeatedly, is to overload the appropriate operators and/or functions. To learn more about overloading operators and functions, please see pages 22-21 through 22-23 of the Using MATLAB manual.
As an example, putting this function minus.m in an @uint8 directory, and putting that @uint8 directory's parent directory on the MATLAB path will allow you to subtract two uint8 objects:
function result=minus(object1, object2)
result=double(object1)-double(object2);
if result<0
result=0;
elseif result>255
result=255;
end
result=uint8(result);
The result is:
A=uint8(7);
B=uint8(5);
C=A-B
In this case, C will contain the uint8 number 2.

More Answers (0)

Products

Community Treasure Hunt

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

Start Hunting!