In today’s lesson, we will discuss the following topics:
1. Operators
2. Relational Operators
3. Logical Operators
4. Special Characters
5. Number Formatting and Converting Between Format Types
6. Data Types and Converting Between Them
Operators
Operators are symbols in MATLAB. When we use operators, MATLAB understands these symbols to execute a certain operation. For example, if we use an equals sign in an equation, MATLAB understands that one side of the equation is equal to the other. Let’s go through a list of the operators you should know (image taken from this link), and note that there are different types (Eg. Arithmetic Operators, Relational Operators, Logical Operators, etc):
Now let’s do some examples using these!
We have already discussed some of the Arithmetic Operators addition, subtraction, multiplication and division in a previous lesson, so I won’t explain them again here. Also, ignore any operators using matrices, as those will be in a future lesson. But let’s take a look at some Relational and Logical Operators, as shown in the table above:
Relational Operators
Relational and logical operators have only two possible values: True and False, but in MATLAB speak these translate to 0 and 1. 0 means false, 1 means true. These are called Boolean Values.
(a) eq: The ‘eq’ operator compares values and determines whether they are equal. We use A==B or eq(A,B), where A and B are the two values we want to compare. This is the difference between a single equals sign (an assignment operator) versus a double equals sign (an equality operator) like we use here. A single equals sign just gives numerical values to a variable. A double equals sign is used to compare the two.
In this example below, I did two different examples (in red) where I created two sets of numbers, A and B. Then I did A==B to compare whether they are equal to each other. The first example has two vectors A and B being compared, and the output after doing A==B shows “0 1 1 0.” In general, MATLAB uses 0 to indicate false, and 1 to indicate true. These are called “Boolean Values,” and I mention them again below.
In example 1, because both A and B are SETS of numbers, MATLAB compares the first value in each set, then the second value, and so on, to see whether they equal one another. If they do, it outputs a 1 in that position, and if they don’t, it outputs a 0. For example, the first number in the set for A is 1, and the first number in the set for B is 3. These don’t equal, so when I did A==B, MATLAB output 0 in the first position to indicate the numbers aren’t equal. For the second example, I used A=5 and B=2 rather than sets of numbers for A and B. Because these numbers are clearly not equal, doing A==B gives us an output of 0 to indicate “false,” as in “they are not true.”
Here’s an example of using eq(A,B) to get the same answer. For this example, where A=5 and B=2, they aren’t equal to one another so the answer is 0. But you could have written it using eq(5,2) instead.
(b) ne: This operator is used to determine inequality. So it will check whether two numbers (or sets of numbers) are equal to one another, and it will output 1 if they are NOT equal (remember 1 means the statement is true), and output 0 if they ARE equal. In this example, A=5 and B=2. There are two ways to write the code, just like with the “eq” operator above. You can use A~=B or ne(A,B). The answer both ways is 1, meaning the two numbers are NOT equal.
(c) Greater Than, Less Than, Greater than or Equal to, Less than or Equal to: These are 4 different operators. Let’s make A=5 and B=2, then compare the two values using all 4 operators (the code is highlighted in blue). MATLAB will output 0 or 1 depending on if the statement is true (1) or false (0). Greater than is >, less than is <, greater than or equal to is >=, and less than or equal to is <=. Notice how I compared A and B using all 4 operators, and because A is greater than B, A>B and A>=B returned outputs of 1, meaning that statement is true. It returned outputs of 0 when I put A<B and A<=B because A is NOT smaller than equal to B, so that’s false.
Logical Operators
(d) AND operator: The AND operator will compare expressions A and B, and give an output containing 1’s and 0’s (1 = true, 0 = false). Think of it as MATLAB answering the question “are both the values in A and B non-zero?” If yes, MATLAB will output a 1. Otherwise, it will output a 0. This is done through A&B or and(A,B)
(e) OR operator: This operator compares expressions A and B and determines whether at least one of them answers the statement. Think of it as MATLAB answering the question “is either A or B non-zero?” If yes, MATLAB outputs 1. Otherwise, if either A or B is 0, MATLAB outputs 0. This is done through A|B or or(A,B)
(f) NOT operator: The NOT operator gives an output of 1 if any value is 0, and outputs 0 if any value is non-zero. This is done through not(A) or ~A. This operator does not compare two different values, so you won’t notice A and B both. MATLAB is answering the question “do we have a zero here?” if yes, it outputs 1, and if not it outputs 0.
(g) && and ||: Having the double and or double or operators mean “shortcut operators.” Putting these in your code will stop MATLAB from evaluating an expression fully. With these double operators, MATLAB will stop evaluating an expression as soon as one part of the expression is true. In some cases, this can avoid errors, such as in the example below: (taken from this link).
When do we use & vs && and | vs ||? Usually when comparing single scalar values, use the shortcut operators && and ||. Use the single & and | when comparing arrays (sets of data).
(h) xor: This is actually a logical function, not an operator, but it was fitting to put it here. The xor function is “exclusive or” which is true if ONLY one variable, but not both, are non-zero. Use xor(A,B) for the syntax. In this example, I have two vectors A and B. When using xor, MATLAB compares each position in the vectors to one another. Looking at the first value in each vector, for A it is a 1 and for B it is a 0 (highlighted). Because only ONE value is a nonzero value (the 1), this satisfies the statement above and outputs a 1 to indicate that the statement is true.
Special Characters
MATLAB has many special characters, such as greek symbols and more. All of these symbols shown here can only be used in plots, such as axis labels and titles, not in equations. Let’s take a look at this list:
Here is an example
Say I want to create a plot and use greek symbols in the title (creating plots will be discussed in a future lesson). I would create the x and y vectors, then plot them. In the code for my title, I have circled the spot where I used the greek letters with the code given in the table above, using the backslash and all. In my graph, I have circled where this produced the output greek symbol.
Number Formatting
MATLAB has different formats for how it displays outputs For example, you can display the numbers in your output in scientific notation, or with a certain amount of numbers after the decimal place. Here is a table with all the different formatting styles in the leftmost column, with an explanation in the middle column, then an example of what the same number would look like with each of the different formats, in the last column on the right:
One of the format styles isn’t really a “format style,” but rather it just gives you positive or negative signs depending on the sign of the number you use. It’s the 4th last style in the table above.
Convert Between Number Formats
Use the “format ____” function. In the blank space, you need to enter a format style from the table above (choose the style you’d like from the left most column).
Take a look at this example below. When I type out “format” followed by the style type, that style type turns purple (eg. the style types ‘long’, ‘shortE’, ‘+’ in purple). Once you type that in and hit the Enter key, any numbers you type after it will take on that style format.
The default style is “format short,” so if you simply type “format,” MATLAB will revert to using format short.
Data Types
Will not discuss all of these in depth (some of them make more sense to add to an upcoming lesson) and some are rarely used for beginner classes.
In computing, a data type, also called the class or simply type, is a characteristic of the data you enter into the computer. This tells the computer how to interpret the data you enter (meaning, the computer will understand how you, the programmer, intends to use that data). Every value you enter into MATLAB has a certain data type associated with it. We can also convert between data types, which I get to later.
Here’s a list of the data types in MATLAB (if you need more infor, check out this link. It has many more related commands to each data type)
(a) Numeric Types: Numerical values are stored in a numeric data type. These are the different numeric data types:
By default, MATLAB stores all numeric values as double-precision floating point (double precision aka double is the numeric type from the table below. This format gives pretty accurate precision for most numerical calculations, so it is used rather than single precision), and you can’t change the default. However, you can choose to store any number as a specific type of numeric data type, as shown in the table a couple paragraphs down.
Side note on Floating Point numbers: Computer memory is limited, and so we cannot store numbers with infinite precision (eg. 0.33333 + 0.333333 + 0.333333 does not quite equal 1 …. you’d get 0.999999 on most computers). At some point you need to cut the decimal off or it would go on forever. But when do we cut it off? To fix this issue, computers use arithmetic called floating point. Floating point numbers are in the form of scientific notation. I won’t get much more in depth here, but just wanted to give a brief overview. This format fits the criteria that:
(a) It can represent the smallest of numbers (eg. atomic size) to the largest of numbers (eg. to trillions and higher)
(b) It will provide about the same accuracy at all these different numbers, from the smallest to the largest (if a computer had to store all those zeroes before and after the decimal in its memory to account for the very very small and very very large numbers, it would be very inefficient!)
(c) It allows for calculations across magnitudes (eg. multiplying a very large and very small number).
Information found at this link.
Both these charts show the various numeric data types in MATLAB. These different types are storage for numerical data. You can save memory and time required to run the program if you use the appropriate integer type for your data. With introductory MATLAB courses, we usually don’t have to do much with changing this from the default, but the middle column of the second chart shows the range of values that each numeric type can store.
Note: All the functions need ‘(x)’ next to them. For example, if you wanted to change a value to an 8-bit signed integer, you’d need int8(x), where x is the value you want to input.
Note: A Signed integer is one that can be both positive and negative. Unsigned integers cannot have negative values, (it can still be 0) but can represent a larger positive value than signed integers can.
For example, to store the number 325.499 as a 16-bit signed integer, use int16(x), where x=325:
To convert between numeric types, use these commands:
For example, if we want to change the vector [-5 5] to an 8-bit unsigned integer, then we change it using ‘cast’ to a new numeric type uint8, then the output is now a vector [0 5], because uint8 only stores values from 0 until 2^8 – 1, which is 255. So -5 was not within 0 to 255, and ‘casting’ the vector into that numeric type changed the output. The syntax for cast is cast(a,’numeric type’). Enter the numeric type you’d like, such as ‘uint8’ here. For ‘a’, enter the value you’d like to change (which was our variable ‘a’ in this case).
(b) Characters and Strings: This data type stores text. We have not yet discussed strings and characters, but just know that when we use letters in MATLAB, they are stored in these data types (if you need more information, check out this link)
(c) Dates and Time: We can use different commands to create time and date arrays
(d) Categorical Arrays: A different data type is one that stores categorical arrays. Categorical arrays are sets of qualitative data, so the data is discrete and nonnumeric. For example, the category of pets with dog, cat, fish, etc would be considered a categorical array. To create a data set into the data type ‘categorical,’ first we create the categories. Hete I have created a variable ‘a’ and set it equal to some different pet categories – dog, fish, cat. In order to create the categories, you need curly brackets around the words, and single quotes around each word itself.
Once you do this, write another line of code to change it into a categorical array. I have made a variable ‘b‘ and set it equal to categorical(a). Where I have the ‘a’ in brackets, you should have the name of whatever your first variable was that stored the category names.
That’s all we need to do! So now when you type ‘class(b)’ into MATLAB, it tells you the type is categorical. Whatever you named your variable should go where I have ‘b’.
(e) Tables: The data type tables is used for data stored in rows or columns in a text file or spreadsheet. Each variable in a table can have a different data type and a different size with the one restriction that each variable must have the same number of rows. There are various commands on how to create a table and convert it into different types.
(f) Timetables: This data type is a type of table that associates a time with each row. There are various commands on how to create a timestable and convert it into different types.
(g) Structures: This data type groups related data using data containers called “fields.” There are various commands for creating a structure data type and more.
(h) Cell Arrays: A cell array is a data type with indexed data containers called cells, where each cell can contain any type of data. Cell arrays usually contain lists of character vectors of different lengths, a mix of strings and numbers, or numeric arrays of different sizes. There are various commands for creating a cell array and more.
(i) Function Handles: A function handle data type represents a function. Functions are covered in a future lesson, so I will leave this one for now.
(j) Map Containers: Objects with keys that index to values, where keys need not be integers
(k) Time Series: A timeseries data type contains information about a changing process/something that happens over time.
To determine the data type of a variable, we can use class(x), where x is the variable you want to determine the data type of. For example, here I have created the word ‘dog’ in the variable ans. Then I check the class of ans and we get ‘char’ as the output, which means that ‘dog’ is the character array data type.
However, to determine whether an input as a specified data type, we can use the following commands. Each command needs (x) next to it. For example iscell(x). x is the input variable that you’re checking the data type for.
Here is an example: If I want to check whether my matrix [1 2 3 4 5] is a character array, I can use ‘ischar([matrix numbers go here])’. It shouldn’t be a character array, because it’s numbers and not letters, but let’s double check:
The output is 0 – that means false, so it is not a character array. But what if we wanted to convert it into one? It would become a word/phrase rather than MATLAB reading it as a numerical matrix. See the next heading for converting data types.
Convert Between Data Types
Take a look at the following table (taken from this link). This shows all the different functions that can be used to convert between data types, and what types it converts from and to:
Now if I wanted to convert my matrix to a character array, I use ‘int2str([matrix numbers go here])’. Then I can check it using ‘ischar(A)’ to confirm whether it is a character data type after I convert it (A is what I named the int2str variable). I now get 1 in the output, which means ‘true’ – we have converted the matrix (previously a numeric data type) to a character data type!
We haven’t discussed making matrices yet, but for the sake of using these commands I will use a matrix example:
The order of operations for all of these operators is the following, from highest to lowest
When MATLAB does numerical calculations, it reads the expressions from left to right and executed them in this order:
(a) BEDMAS, which I discussed in a previous session
(b) Relational Operators
(c) Logical “not” operators
(d) Logical “and” operator
(e) Logical “or” operator