%[text] %[text:anchor:T_AD2FD213] # 454MI: Introduction to MATLAB - Part 2
%[text] %[text:anchor:T_E0678B70] # Numbers, Arithmetic Operations, Formats and Variables
%[text]
%[text] This is the second MATLAB live script of the collection ***Using MATLAB in the 454MI "******Data Driven Digital Systems***" course, devoted to introduce the MATLAB/Simulink environment and tools for solving practical problems related to the topics of the 454MI course, i.e. performance analysis of dynamic systems, parametric estimation, identification of models from data, and prediction of the evolution of dynamic systems.
%[text] Use [this link](file:./usingMATLAB_454MI_Data_Driven_Digital_Systems.m) to go back to the main live script of the collection.
%[text]
%[text:tableOfContents]{"heading":"Table of Contents"}
%[text]
%%
%[text] %[text:anchor:H_EEFC1786] ## Objectives
%[text]
%[text] The aim of this module is to enable you to enter an arithmetic expression in MATLAB and understand the results produced, particularly when these results involve scientific notation, complex numbers and `Inf` and `NaN`.
%[text] What you should know by the end of this module:
%[text] - the importance of being very precise when entering arithmetic expressions, particularly when brackets are required;
%[text] - how to enter numbers using scientific notation and how to change the format of the answer displayed in the MATLAB Command Window;
%[text] - how to enter complex numbers and how to find real and imaginary parts;
%[text] - the meaning of `Inf` (infinity) and `NaN` (Not a Number);
%[text] - what is a valid variable name;
%[text] - how to use `=` to assign a value to a variable and how to clear a variable;
%[text] - MATLAB predefined variables (constants), pi, i, j, eps, etc. ;
%[text] - how to examine the value of a variable, how to list the variables in the current workspace, how to get extra information about the variables and finally how to remove them from the current workspace. \
%%
%[text] %[text:anchor:H_926AECFD] ## MATLAB as calculator
%[text]
%[text] This is the simplest way of using it: evaluating numerical expressions.
%[text] Suppose we want to evaluate the numerical expression
%[text]{"align":"center"} $4+\\displaystyle \\sqrt{2}-\\Big\[\\sin\\left(\\displaystyle \\frac{\\pi}{5} \\right) \\Big\]^{2}+e^{2}$
%[text] Simply
4 + sqrt(2) - sin(pi/5)^2 + exp(2) %[output:0adc9151]
%[text] The result is assigned to the **predefined variable** **`ans`**.
%%
%[text] %[text:anchor:H_04A7197E] ## Arithmetic operations
%[text]
%[text] The most common arithmetic operations in MATLAB are
%[text] - Addition $a+b \\quad \\Leftrightarrow \\quad$`a+b`
%[text] - Subtraction $a-b \\quad \\Leftrightarrow \\quad$`a-b`
%[text] - Multiplication $a\\cdot b \\quad \\Leftrightarrow \\quad$`a*b`
%[text] - Division $a/b \\quad \\Leftrightarrow \\quad$`a/b`
%[text] - Powers $a^b \\quad \\Leftrightarrow \\quad$`a^b` \
%[text] This is just like on a calculator, in spreadsheets (Excel) and most programming languages.
%[text] %[text:anchor:H_D951F635] ## Order of Operations
%[text]
%[text] In MATLAB (as many other programming languages) operations are performed in the following order:
%[text] 1. expressions in brackets: `( )` ;
%[text] 2. powers: `^` ;
%[text] 3. multiplication and division: `*` , `/` ;
%[text] 4. addition and subtraction: `+` , `-` . \
%[text] Operations of the **same precedence**, for example multiplication and division, are **evaluated from left to right**.
%[text] In ordinary written mathematics, we sometimes leave out brackets and rely on the fact that an intelligent human will understand where they ought to go. In contrast, computers obey precisely the rules for evaluating expressions. If unsure, adding extra brackets (parentheses) will not hurt.
%[text] %[text:anchor:H_A1A25E40] ### A few Examples
1+2*3 % Which operation has higher precedence? %[output:45fe0819]
(1+2)*3 % And now? %[output:50ed5f2f]
%[text] Remember that operations of the same precedence are evaluated left to right:
24/2/3 % The same result as the the second case. %[output:8c184190]
24/(2*3) % This version is usually clearer. %[output:1ded51f4]
%[text] A final example:
5^4^3 %[output:0f182190]
5^(4^3) % Note the different result! %[output:885f1eb7]
(5^4)^3 % This is the same as the first case, but clearer. %[output:3d76c39b]
%[text]
%%
%[text] %[text:anchor:H_F83B4E81] ## Changing the Displayed Format
%[text]
%[text] By default, MATLAB displays 5 decimal digits, unless the number is too big or too small, when it switches to [scientific notation](internal:H_4BFE51EF). The format of the answers displayed in the command window can be changed using the **format** command.
help format %[output:6bc4a4fe]
%[text] **Pay attention**: format does **NOT** affect how numbers are stored or calculations are done in MATLAB. It **only** affects how numbers are displayed.
%[text] %[text:anchor:H_1BA11AC2] ### A Simple Example
format short
x = 3 + 11/16 + 2^1.2 %[output:49f0edbd]
format compact
x = 3 + 11/16 + 2^1.2 %[output:69959458]
format long eng
x = 3 + 11/16 + 2^1.2 %[output:32870c19]
format long
x = 3 + 11/16 + 2^1.2 %[output:0e944cfa]
%[text] %[text:anchor:H_59408B2E] ###
%[text] %[text:anchor:H_81EDB942] ###
%%
%[text] %[text:anchor:H_8724821D] ###
%[text] %[text:anchor:H_4BFE51EF] ### Scientific Notation
%[text] For very large numbers or very small numbers it is more convenient to express the number in scientific notation using a power of 10.
3.6e+12 %[output:4f8cbbd3]
5.2e-9 %[output:94623b71]
2^30
2^(-40)
0.5/0.1-5
0.7/0.1 -7 % Sometimes the result may not be what you expect.
%%
%[text] %[text:anchor:H_1A73A6CF] ## Complex Numbers
%[text] MATLAB allows and works with complex numbers. All arithmetic with complex numbers works in the usual way.
%[text] You may use both $i$ and $j$ to denote the imaginary unit, if you did not already define any variable named $i$ or $j$(see below how to set valid variable names).
%[text] %[text:anchor:H_B7C04024] ### Example
%[text] Define the complex number $2+3\\,i$
2+3*1i %[output:4613d479]
complex(0, 1) %[output:656be594]
2+3i %[output:3b3af7c1]
2+3j % Any of these three expression works. %[output:4ddcdcde]
%[text] Define the complex expression
%[text]{"align":"center"} $\\displaystyle \\frac{2+3\\,i}{4+6\\,i}$
(2+3*1i)/(4+6*1i) %[output:4be86ae3]
%%
%[text] %[text:anchor:H_5926CE83] ### Special functions for complex numbers
%[text]
%[text] A MATLAB function to **create a complex number**: create the complex number $2+3\\,i$
complex(2, 3) % the 1st argument is the real part, the 2nd arg. is the imaginary part
%[text] A MATLAB function to **get the real part** of the complex number $2+3\\,i$
real(2+3i)
%[text] A MATLAB function to **get the imaginary part** of the complex number $2+3\\,i$
imag(2+3j)
%[text] A MATLAB function to **get the modulus** of the complex number $\\displaystyle \\frac{2+3\\,i}{4+6\\,i}$
abs((2+3*1i)/(4+6*1i))
%[text] A MATLAB function to **get the argument** of a complex number (in radians)
angle(+1+1j)
rad2deg(angle(+1+1j))
rad2deg(angle(+1-1j))
rad2deg(angle(-1-1j))
rad2deg(angle((2+3*1i)/(4+6*1i)))
rad2deg(angle(2+3*1i))
rad2deg(angle(4+6*1i))
%%
%[text] %[text:anchor:H_FCE550A9] ## Special Values for Infinity and for Undefined Operations
%[text] MATLAB uses the IEEE 754 standard for floating point numbers, to provide approximations to the real numbers. This standard, which is used in virtually every current computer microprocessor, specifies how floating point numbers are stored and also includes special values for infinity and for undefined operations.
%[text] %[text:anchor:H_53C58F88] ### Infinity (Inf)
%[text] Operations that would result in a mathematical infinity give a result of `Inf`, while those that would result in minus infinity give `-Inf`.
1/0
-3/0
%[text] %[text:anchor:H_DFEB469D] ### Not a Number (NaN)
%[text] Operations whose value cannot be mathematically determined result in a *Not a Number*.
0/0
%[text] %[text:anchor:H_053476F8] ### Propagation of Inf and NaN in Calculations
%[text] Both Inf and Nan propagate in calculations without producing any error message.
1e-10*Inf
5*NaN
%[text] Operations involving `Inf` and/or `NaN` are also significantly slower than those using standard floating point numbers.
%[text]
%[text] Operations involving `Inf` can produce a `NaN`.
Inf-Inf
Inf+Inf
%[text] Once you have produced a `NaN`, it affects all calculations from then on:
1e-32*NaN
NaN-NaN
%%
%[text] %[text:anchor:H_D6254615] ## Variables
%[text]
%[text] Variables are essential to store the result of a calculation so it can be subsequently used in a later calculation. This not only makes your programs much more efficient, but also makes them much easier to understand.
%[text] %[text:anchor:H_B7BEC9B1] ### Variable Names
%[text] A variable name is a sequence of letters, numbers and underscores "\_", **starting with a letter**.
%[text] The following are invalid variable names. Try to insert one of those variable name in the code box below, run the section and see what message you will obtain
%[text] ```matlabCodeExample
%[text] 1x % invalid variable name!
%[text]
%[text] _x % another invalid variable name
%[text] ```
%[text]
% insert one of the two invalid variable declaration here and see the
% resulting error message
x1
%[text] Then insert one of the following valid variable names
%[text] ```matlabCodeExample
%[text] x1 % valid variable name
%[text]
%[text] x_ % valid variable name
%[text] ```
%[text] You should obtain a different error message: indeed the variable name is valid, but the variable does not exist in the Matlab Workspace.
%[text]
%[text] **Length of variable names**: although a variable name may have any length, MATLAB only recognizes the first "few" characters. How many characters are recognized is specified by the Matlab command `namelengthmax` (which is typically 63).
%[text] %[text:anchor:H_95D52CC5] ###
%[text] %[text:anchor:H_8AB0DFEE] ### Warnings
%[text] - MATLAB is case sensitive; x and X are different variables!
%[text] - You should not use a variable name that clashes with a constant, for example `pi`, or with a MATLAB command, as `var (`Hint: `help var` )
%[text] - Names cannot be MATLAB keywords, for example `for`, `if`, `end`, etc. \
%%
%[text] %[text:anchor:H_3439683D] ### Assigning Values to Variables
%[text] Matlab uses `=` to assign a value to a variable.
%[text] **Note**: the left-hand-side of the `=` must be a valid variable name, while the right-hand-side must be a valid expression.
a = 1 %[output:6a5a25e8]
b = -1 %[output:679ad411]
c = -2 %[output:1551a3c8]
delta = b^2 - 4*a*c %[output:6cd41fcd]
x1 = (-b + sqrt(delta))/(2*a) %[output:297766c3]
x2 = (-b - sqrt(delta))/(2*a) %[output:0d054db9]
%%
%[text] %[text:anchor:H_5274375C] #### Suppressing output
%[text] When Matlab does a calculation and assigns the result to a variable, the result is echoed to the command window.
%[text] Sometimes, especially when dealing with large vectors or matrices, it is very useful to keep the screen uncluttered by unwanted output. This is simply done by adding a semicolon ; to the end of the command
x = 2;
y = 4;
z = x*y;
%%
%[text] %[text:anchor:H_128381AA] ### Useful Commands
%[text]
%[text] There are several useful commands that allow you to see what variables you have created and if necessary remove some or all of them.
%[text] Please remember, you can always get more information on a command using the `help` command.
%[text] %[text:anchor:H_B99BA0BC] #### List of the Variables
%[text] - to list all the variables in the current MATLAB workspace \
who
who x* % This command lists all the variables starting with the (lower case) letter x.
%[text] - to lists the variables, but obtaining extra information about their size and data type \
whos
whos x*
%%
%[text] %[text:anchor:H_7C09FF5E] #### Clearing Variables
%[text] To remove a variable, use the `clear` command
clear x1
whos
%[text] %[text:anchor:H_F63B0C6B] ##
%%
%[text] %[text:anchor:H_F52F7665] ## Predefined Constants
%[text]
%[text] When you start MATLAB, some variables already have predefined values:
%[text] - the constant $\\pi$ \
pi
%%
%[text] - the imaginary unit of complex numbers $0+i$ or $0+j$ \
1i
1j
%%
%[text] - the largest double precision number and the smallest positive double precision number \
realmax % the largest double precision number
4*realmax % What did you expect as the result?
realmin % the smallest positive double precision number
%[text] MATLAB uses IEEE 754 standard **double precision** to store floating point numbers which approximate the real numbers. The characteristics of double precision arithmetic are described by the relative machine precision, also known as the **machine epsilon**
eps
%[text]
%[text] %[text:anchor:H_C70D46C7] #### Caveat
%[text] You can give these variables new values. If you do so you may get strange effects afterwards!
%[text]
%%
%[text] %[text:anchor:H_BE2690D8] ## Summary
%[text]
%[text] Using this live script you have:
%[text] - seen how arithmetic expressions are evaluated in MATLAB and how to use brackets to get the desired result or make an expression clearer;
%[text] - learned how to enter numbers using scientific notation;
%[text] - learned how to change the format of the result displayed in the MATLAB Command Window;
%[text] - learned how to enter complex numbers and how to find real and imaginary parts;
%[text] - learned about Inf (infinity) and NaN (Not a Number);
%[text] - learned what are valid names for variables in MATLAB;
%[text] - learned how assign values to variables using the = operator;
%[text] - learned how to display the value of a variable;
%[text] - learned how to see what variables have been defined and how to clear a variable from your workspace. \
%[text]
%[text] %[text:anchor:H_B713125A] #### Back to the Index
%[text] Use [this link](file:./usingMATLAB_454MI_Data_Driven_Digital_Systems.m) to go back to the main live script of the collection.
%[text]
%[text] %[text:anchor:H_C8A86778] #### Back to the Previous Part: Starting MATLAB
%[text] Use [this link](file:./Intro_MATLAB4DDDS_p1.m) to go back to the previous live script of this collection.
%[text]
%[text] %[text:anchor:H_A2D5477B] #### Go to the Next Part: Vectors & Matrices
%[text] Use [this link](file:./Intro_MATLAB4DDDS_p3.m) to go to the next live script of the collection.
%[text]
%[text]
%[text]
%[appendix]{"version":"1.0"}
%---
%[metadata:view]
% data: {"layout":"inline","rightPanelPercent":40}
%---
%[output:0adc9151]
% data: {"dataType":"textualVariable","outputData":{"name":"ans","value":" 12.457778158491220"}}
%---
%[output:45fe0819]
% data: {"dataType":"textualVariable","outputData":{"name":"ans","value":" 7"}}
%---
%[output:50ed5f2f]
% data: {"dataType":"textualVariable","outputData":{"name":"ans","value":" 9"}}
%---
%[output:8c184190]
% data: {"dataType":"textualVariable","outputData":{"name":"ans","value":" 4"}}
%---
%[output:1ded51f4]
% data: {"dataType":"textualVariable","outputData":{"name":"ans","value":" 4"}}
%---
%[output:0f182190]
% data: {"dataType":"textualVariable","outputData":{"name":"ans","value":" 244140625"}}
%---
%[output:885f1eb7]
% data: {"dataType":"textualVariable","outputData":{"name":"ans","value":" 5.421010862427522e+44"}}
%---
%[output:3d76c39b]
% data: {"dataType":"textualVariable","outputData":{"name":"ans","value":" 244140625"}}
%---
%[output:6bc4a4fe]
% data: {"dataType":"text","outputData":{"text":" format<\/strong> Set output display format.\n fmt = format<\/strong> returns the current display format.\n \n format<\/strong> style changes the output display format. For a description of\n possible values for style, see details below.\n \n fmt = format<\/strong>(style) stores the current display format in fmt and then\n changes the display format to the specified style.\n \n format<\/strong>(fmt) changes the output display format to the fmt returned by a\n previous call to format<\/strong>.\n \n format<\/strong> does not affect how MATLAB computations are done. Computations\n on float variables, namely single or double, are done in appropriate\n floating point precision, no matter how those variables are displayed.\n Computations on integer variables are done natively in integer. Integer\n variables are always displayed to the appropriate number of digits for\n the class, for example, 3 digits to display the INT8 range -128:127.\n format<\/strong> SHORT and LONG do not affect the display of integer variables.\n \n format<\/strong> DEFAULT may be used to restore the default display format,\n which is SHORT for numeric format and LOOSE for line spacing.\n \n format<\/strong> may be used to switch between different output display formats\n of all float variables as follows:\n format<\/strong> SHORT Short fixed point format with 4 digits after the\n decimal point.\n format<\/strong> LONG Long fixed point format with 15 digits after the\n decimal point for double values and 7 digits after\n the decimal point for single values.\n format<\/strong> SHORTE Short scientific notation with 4 digits after the\n decimal point.\n format<\/strong> LONGE Long scientific notation with 15 digits after the\n decimal point for double values and 7 digits after\n the decimal point for single values.\n format<\/strong> SHORTG Short fixed format or scientific notation,\n whichever is more compact, with a total of 5 digits.\n format<\/strong> LONGG Long fixed format or scientific notation, whichever\n is more compact, with a total of 15 digits for\n double values and 7 digits for single values.\n format<\/strong> SHORTENG Engineering format with 4 digits after the decimal\n point and a power that is a multiple of three.\n format<\/strong> LONGENG Engineering format that has exactly 15 significant\n digits and a power that is a multiple of three.\n \n format<\/strong> may be used to switch between different output display formats\n of all numeric variables as follows:\n format<\/strong> HEX Hexadecimal format.\n format<\/strong> + The symbols +, - and blank are printed\n for positive, negative and zero elements.\n Imaginary parts are ignored.\n format<\/strong> BANK Currency format with 2 digits after the decimal\n point.\n format<\/strong> RATIONAL Approximation by ratio of small integers. Numbers\n with a large numerator or large denominator are\n replaced by *.\n \n format<\/strong> may be used to affect the spacing in the display of all\n variables as follows:\n format<\/strong> COMPACT Suppress excess blank lines to show more output.\n format<\/strong> LOOSE Add blank lines to make output more readable.\n \n Example:\n format short, pi, single(pi)\n displays both double and single pi with 5 digits as 3.1416 while\n format long, pi, single(pi)\n displays pi as 3.141592653589793 and single(pi) as 3.1415927.\n \n format, intmax('uint64'), realmax\n shows these values as 18446744073709551615 and 1.7977e+308 while\n format hex, intmax('uint64'), realmax\n shows them as ffffffffffffffff and 7fefffffffffffff respectively.\n fmt=format(\"hex\"), intmax(\"uint64\"), format(fmt)\n shows ffffffffffffffff and restores the previous display format.\n The HEX display corresponds to the internal representation of the value\n and is not the same as the hexadecimal notation in the C programming\n language.\n \n See also disp<\/a>, display<\/a>, isnumeric<\/a>, isfloat<\/a>, isinteger<\/a>.\n\n Documentation for format<\/a>\n Other uses of format<\/a>\n\n","truncated":false}}
%---
%[output:49f0edbd]
% data: {"dataType":"not_yet_implemented_variable","outputData":{"columns":"1","name":"x","rows":"1","value":"5.9849"},"version":0}
%---
%[output:69959458]
% data: {"dataType":"not_yet_implemented_variable","outputData":{"columns":"1","name":"x","rows":"1","value":"5.9849"},"version":0}
%---
%[output:32870c19]
% data: {"dataType":"textualVariable","outputData":{"name":"x","value":" 5.98489670999407e+000"}}
%---
%[output:0e944cfa]
% data: {"dataType":"textualVariable","outputData":{"name":"x","value":" 5.984896709994070"}}
%---
%[output:4f8cbbd3]
% data: {"dataType":"textualVariable","outputData":{"name":"ans","value":" 3.600000000000000e+12"}}
%---
%[output:94623b71]
% data: {"dataType":"textualVariable","outputData":{"name":"ans","value":" 5.200000000000000e-09"}}
%---
%[output:4613d479]
% data: {"dataType":"textualVariable","outputData":{"name":"ans","value":" 2.000000000000000 + 3.000000000000000i"}}
%---
%[output:656be594]
% data: {"dataType":"textualVariable","outputData":{"name":"ans","value":" 0.000000000000000 + 1.000000000000000i"}}
%---
%[output:3b3af7c1]
% data: {"dataType":"textualVariable","outputData":{"name":"ans","value":" 2.000000000000000 + 3.000000000000000i"}}
%---
%[output:4ddcdcde]
% data: {"dataType":"textualVariable","outputData":{"name":"ans","value":" 2.000000000000000 + 3.000000000000000i"}}
%---
%[output:4be86ae3]
% data: {"dataType":"textualVariable","outputData":{"name":"ans","value":" 0.500000000000000"}}
%---
%[output:6a5a25e8]
% data: {"dataType":"textualVariable","outputData":{"name":"a","value":" 1"}}
%---
%[output:679ad411]
% data: {"dataType":"textualVariable","outputData":{"name":"b","value":" -1"}}
%---
%[output:1551a3c8]
% data: {"dataType":"textualVariable","outputData":{"name":"c","value":" -2"}}
%---
%[output:6cd41fcd]
% data: {"dataType":"textualVariable","outputData":{"name":"delta","value":" 9"}}
%---
%[output:297766c3]
% data: {"dataType":"textualVariable","outputData":{"name":"x1","value":" 2"}}
%---
%[output:0d054db9]
% data: {"dataType":"textualVariable","outputData":{"name":"x2","value":" -1"}}
%---