The MATLAB package is employed in wide ranges of engineering and scientific computing applications and is associated with the dynamic system simulation package called Simulink. The package has a few advantages and remarkable strengths, such as user-friendly and intuitive programming syntax, high-quality numerical algorithms for various numerical analyses, powerful and easy-to-use graphics, simple command syntax to perform computations, and many add-ons as toolboxes and real and complex vectors and matrices, including sparse matrices as fundamental data types.
There are diverse application areas of the package, i.e. simulation of various systems such as vehicle performances, mapping of the human genome, financial analysis in emerging economies, microbiology applications in diagnosis and treatment of small organisms, dynamic simulations of large ships in down-scaled laboratory models, simulation of the next generation network audio products, teaching computer programming to undergraduates with real-time laboratory tests and measurements, and image processing for underwater archeology and geology.
In this chapter, we discuss some essential key features of the graphical user interface (GUI) of MATLAB, how to use the help tools and library sources, how to adjust the format options and accuracy and precision settings, how to create various variables and variable structures, and how to employ the M/MLX editors to write and edit scripts/programs.
MATLAB’s Menu Panel and Help
The MATLAB application can be launched from the Windows operating system by clicking the icon/shortcut from the desktop window or choosing Start ➤ All Programs ➤ . As MATLAB loads, the user’s last preserved data, files, entries, last 20 commands (by default), and menu bar and tools with the last preferences all appear. MATLAB’s graphical user interface (GUI) tools and windows are customizable. Users can easily manipulate, customize, and change preferences of the package according to their needs. Figure 1-1 shows the default main window of MATLAB 2018a. It must be noted that the package’s GUI menu and tools have changed over the years in an effort to make the package more user friendly and the tools more intuitive. The default window has the main menu tools, a Current Directory indicator, and Command, Workspace, and Command History windows. These windows can be docked/undocked or opened in a separate window, closed or removed from the main window, or dragged from one pane to another and maximized or minimized.
Tools and toolbars are grouped into three menus—HOME, PLOTS, and APPs (see Figure 1-2). The HOME tab contains all the main tools. It’s where you can create and delete new files and variables, import data, access the code analyzer, launch Simulink, change the MATLAB package desktop layout change options, set the path, and access add-ons and help options.
The Current Directory window is in the left pane by default. This window shows all the files in the directory and the folder directory.
The Command Window is in the central pane (by default). All commands and/or (small) scripts/codes can be entered directly after . By clicking on (see Figure 1-4) in the Command Window, you can view all built-in functions and MATLAB toolboxes. This option is only available starting from MATLAB version R2008a. All installed toolboxes can also be viewed or accessed by clicking on the APPS tab (see Figure 1-2), which is available in later versions of MATLAB, starting with the R2010a version.
The Workspace pane of the default desktop window shows the current entries and saved variables during the session. These entries are saved temporarily until the MATLAB application is closed. All essential attributes and properties of entries/variables (variable names, values, and types) are displayed in the workspace.
Note
Before discussing the help options, I need to highlight one important point concerning comments. In MATLAB, users can write necessary hints and help remarks as comments within the M/MLX-files and in the Command Window. Comments need to start with an % sign. There are other options for adding comments, which I will discuss later when writing M/MLX-files.
- 1.
Quick help can be obtained from the Command Window with the help command. In this case, help is displayed from MATLAB’s built-in commands/functions as well as within the user’s function files. This is a quick way to obtain help.
>> help clock - 2.
Extensive (detailed) help, with examples, is displayed in the Help Library window with the following commands, but only if such a function file (e.g., clock) exists.
>> doc clock>> docsearch clock - 3.
You can access an extended list of M-files containing a keyword from the Command Window by using the following help command. Note that this option is much slower than the other two search options, due to its exhaustive search for the keyword.
>> lookfor clock - 4.
You can view the function file explanation in the Help Library by using the following command, but only if such a function file (e.g., clock) exists.
>> helpwin clock - 5.
All extended tips, examples, and command syntax can be viewed from the Help Library (displayed in Figure 1-3), which can be accessed by clicking on the Help menu options.
- 6.
You can use the F1 keyboard key to open the Help Library and documentation.
- 7.
By clicking on the Help menu from the main panel, you can access various help resources from MathWorks, such as its Help Library resources, web resources, demo examples, updates, trials, and so forth.
There are a number of hands-on help resources available online, including MathWorks website academia, the user community’s published scripts and file exchanges[1], and the MATLAB answers forum [2], where learners/users/developers post their questions and seek answers, or conversely post their answers to posted questions. It also includes function files, Simulink models, online forums, tutorials of numerous universities [3], and personal web pages of professors and researchers [4], just to name a few.
The MATLAB Environment
The Preferences window shown in Figure 1-6 will pop up. The directories/paths to the current directory can also be altered and new paths can be added, as shown in Figure 1-7.
Working in the Command Window
The addpath() command might also be helpful in scripts, to read or load data from a specific folder or directory. For short commands and calculations and/or to view attributes of the available variables in the current directory, use the Command Window. However, for series of commands and longer scripts, it is more efficient to use script editors, such as the M-file and MLX-file editors.
The MATLAB application has a few files that are recognizable by their extensions. They are .M, .MLX, .MAT, .BI, and .FIG. M-files are used to write programs/scripts/function files. MLX-files (Live M-files) are used to write programs/scripts/function files and see the computation results within the MLX-file editor window. MAT-files are used to save all types of variables available in the workspace and can be accessed easily from M/MLX-files and the Command Window. Among these files, .BI files are used for built-in files of MATLAB and .FIG files are used to save figure windows in MATLAB. In addition, the Simulink application has three types of files—mdl, .slx, and .slxc. They are used to build and simulate Simulink models and can also be recalled/simulated from MATLAB without opening them. I will discuss the essential features of these files and how to use them in later sections of the book.
While using the Command Window for simple calculations and data generation and processing is sufficient, the keyboard’s up-arrow key can be used to avoid having to retype the previously entered commands and entries. For example, if you entered >> A1 = [1, 2, 4, -5, 6]; B = A+2 in the Command Window and then needed to make changes to these entries, you could use the up-arrow key after typing this: >> A. MATLAB will automatically recall your previous entry.
Command Window and Variables
MATLAB is case-sensitive and all of its built-in commands are lowercase. When you perform computations, you assign a name to the result of the computation. The assigned name is the variable name. The result of the computation is saved in the MATLAB workspace under the given variable names. For example, >> A =13; B = A*2 means that the variable called A is equal to 13 and a variable called B is equal to 2 multiplied by A.
Using Variables
Note
MATLAB is case sensitive so it recognizes the variables called a and A as two different variables.
After entering a few starting letters of a variable name or built-in command/function name in the Command Window, you can use the TAB key from the keyboard to access matching commands/functions, including your developed function files. For example, if you typed >> AB and then pressed TAB, the rest of ABCD variable calculation expression would appear as an option.
Another useful feature of the Command Window is using the keyboard’s up-arrow (↑) to recall previously typed variables or commands. You simply type a few starting letters of any previously typed commands or function names and then press the up-arrow (↑). For example, >> f↑ recalls the previously typed-in command, >> format long. Moreover, the up-arrow (↑) can be associated with the TAB key to recall previously entered commands in the Command Window.
The values and attributes of all variables entered in the Command Window will be saved in the workspace until you clean up the workspace by deleting the variables using the clear, clearvars, or clear all command or by using the right and left mouse button options to select the variables and delete them. In addition, all of the variables and their attributes are saved in the workspace until the MATLAB package is closed.
clc for cleaning up the Command Window and starting with a blank Command Window
clear and clearvars for removing all variables saved in the workspace
clear all for removing all variables as well as temporarily compiled and saved machine codes of M-files, breakpoints, and debug settings
From these examples, it is clear that MATLAB reads every entry as an array/matrix. For example, scalar is read by MATLAB as an array of size 1-by-1. This attribute of MATLAB is logically linked to its name, MATrix LABoratory. MATLAB’s default storage (memory allocation) is double precision, which is the maximum available space allocated. However, for memory efficiency and faster calculation purposes, other storage formats can also be used. MATLAB supports single precision or integer type and int8 … 64, uint8 …64 storage format types. Table 1-1 shows how data can be saved in every storage class type and the conversion function used in MATLAB for each type.
Note
MATLAB’s default storage type is double. However, that can be changed to single precision or integer types—int8 …64, uint8 …uint64—by specifying or converting the values of the variables/data.
Data Storage Format Types in MATLAB
- |
The Command Window’s history pane is a good way to review all of the entries that will be kept unless you delete them. You can also change the setting in the Preferences window to clear the history of entries after ending the session.
Or use Ctrl+Q from the keyboard to quit.
An alternative way to exit is by clicking close (the x) in the upper-right corner of the main window. This will close the whole package.
When to Use the Command Window
To perform short calculations
To view error and warning messages from commands or/and after executing M-files, MLX-files, and SLX/MDL Simulink models
To view variable attributes saved in the workspace and files in the current directory
To view the contents of MATLAB compatible files
To execute MATLAB files, such as M-files, MLX-files, SLX/MDL-files, and MAT-files
To get hands-on, quick help with MATLAB commands/functions and user-created function files
To make adjustments to the display formats of numerical data
To add/remove a path/directory
To create/delete/save variables and files
- 1)To view and analyze common errors and interpret error messages:>> F16=65535; Fint_16=uint16(F16); Fnew2 = Fint_16+1;>> Fnew+2 % The variable Fnew does not exist in the workspaceUndefined function or variable 'Fnew'.>> clar F16 % Typo error: "clar" instead of "clear"Undefined function or variable 'clar'.>> CLear % Typo error: "CLear" instead of "clear". Note: MATLAB case-sensitiveUndefined function or variable 'CLear'.Did you mean:>> clear % MATLAB automatically suggests closest command's correct syntax>> B=-2; C=1/2; BC=B/.C; % Illegal operation: B/.C instead of B/C;B=-2; C=1/2; BC=B/.C;↑Error: Unexpected MATLAB operator.>> B=-2; C=1/2; BC=B /*C; % Illegal operation: B/*C instead of B/C;B=-2; C=1/2; BC=B /*C;↑Error: Invalid use of operator.>> % Let's create a two-row matrix containing two elements, viz. B, C in the >> % first row and F16 in the second row.>> BCF = [B, C; F16] % Number of elements in row 1 does not match with the ones in row 2Error using vertcatDimensions of arrays being concatenated are not consistent.>> % Let's try to create a row matrix with elements separated with "," and >> % space and ".">> BCF = [B, C. F16] % Error is a misused "." instead of "," but not dot indexing as shownDot indexing is not supported for variables of this type.>> BCF = [B, C, F16] % This is the anticipated correct command.
- 2)To save the variables saved in the workspace in a *.mat file:>> save MYdata.mat % Saves all variables residing in the workspace in MYdata.mat file>> save('MYdata.mat') % The same as above>> save MYdata.mat F16 Fnew2 % Saves the variables F16, Fnew2 in MYdata.mat file>> save('MYdata.mat', 'F16 ', 'Fnew2 ') % The same as above>> save MYdata.mat F* % Saves all variables whose name starts with F (in the workspace)
- 3)To obtain quick help:>> help formatformat Set output format.format with no inputs sets the output format to the default appropriatefor the class of the variable. For float variables, the default isformat SHORT. ...>> help dirdir List directory.dir directory_name lists the files in a directory. Pathnames andasterisk wildcards may be used. A single asterisk in the path touching>> help whatwhat List MATLAB-specific files in directory.The command what, by itself, lists the MATLAB specific files found ...>> help which--- help for which ---which Locate functions and files.which ITEM displays the full path for ITEM. ITEM can include a partialpath, complete path, relative path, or no path. If ITEM includes apartial path or no path, ...
- 4)To view MATLAB compatible files:>> type QQQ.txt % Note: the file QQQ.txt was available in the current directoryCY bBb 88AH AAAA+ 98CWW AAAA+ 98...>> type MYfile.mlx % Note: the file MYfile.mlx was available in the current directoryN=13;M=randi(N,9);stairs(M, 'bd-')>> type myfun.m % Note: the file myfun.m was available in the current directoryfunction f=myfun(x)f=[2*x(1)-x(2)-exp(-x(1));-x(1)+2*x(2)-exp(-x(2))];End
- 5)To create, open, and execute MATLAB files (M-files, MLX-files, MDL/MLX-files, and MAT-files):>> edit TRY1.m % To create a new M-file called TRY1.mlx>> edit MYfile.mlx % To create a new MLX-file called MYfile.mlx>> open('TRY1.m') % To open the file if it is residing in the current directory>> run('...TRY1.m') % Directory and a file name is needed, if it is outside of the current dir.>> TRY1 % To execute the file if it is residing in the current directory>> open('MYfile.mlx') % To open the file if it is residing in the current directory>> MYfile % To execute the file if it is residing in the current directory>> load MYdata.mat % Load contents of MYdata.mat (existing in the current directory)>> load('MYdata.mat') % The same as above
- 6)
To delete files in the current directory or variables residing in the workspace.
Warning Be careful when using these delete commands, because they delete files that cannot be recovered.>> delete TRY1.m % Deletes the file TRY1.m residing in the current directory>> delete MYfile.mlx % Deletes the file MYfile.mlx residing in the current directory>> delete QQQ.txt % Deletes the file QQQ.txt residing in the current directory>> delete *.txt % Deletes all *.txt files in the current directory>> delete *.mlx % Deletes all *.mlx files in the current directory>> delete DA*.txt % Deletes all *.txt files whose name starts with DA...>> delete *.asv % Deletes all *.asv files (autosave) of MATLAB in the current directory - 7)To view the current directory, change a directory, create a new directory, and remove a directory from the MATLAB path:>> MD = pwd % Shows the current directory and assigns to a character type of variable: MD>> cd C:Userssulaymon.eshkabilovDocumentsMATLAB % Change to this directory>> cd('C:Userssulaymon.eshkabilovDocumentsMATLAB') % The same as above>> mkdir MYBook % Creates a new folder (directory) inside the current directory>> mkdir('MYBook') % The same as above>> mkdir c:Userssulaymon.eshkabilovBOOK % The same as above with a full path>> addpath C:Documents % Adds this path (C:Documents) to the MATLAB's search>> addpath('C:Documents') % The same as above>> rmdir('MYtask') % Removes the directory (folder: MYtask) including its contents from the hard disk>> rmdir c:Userssulaymon.eshkabilovTASK % Removes the directory: TASK
Note
MATLAB supports wildcards (the asterisk *) when deleting and saving files and variables in the current directory and workspace. For example, >> delete M*.mat deletes all the *.mat files whose names start with M. The >> save MYdata.mat B* command saves all variables whose names start with B. The >> clearvars A* command clears all variables whose names start with A.
Many of the operations performed in the Command Window, such as performing calculations and analyses and viewing variables or file contents, can also be done other ways. For example, most of the operations carried out in the Command Window can also be done via GUI tools. You can create new variables , delete them , or open them .
Similarly, you can create a MATLAB file with or an M-file with or open an existing MATLAB file with . You can delete the files via the right and left mouse button options. You can also view the current directory or change it using .
One of the most essential functions of the Command Window that cannot be done easily with GUI tools is viewing the error and warning messages obtained while and after executing M-files, MLX-files, and MDL/SLX-files. This is essential for good programming. Another good use of the Command Window is to obtain quick help with MATLAB commands/functions.
Different Variables and Data Sets in MATLAB
MATLAB supports several different data types—numeric, character, logical, table, cell, structure, and function handle. The flowchart in Figure 1-10 shows the hierarchy of all data types supported in MATLAB that can be used for data storage. Note that the function handle can also take vectors (row or column vectors), not only scalar numbers.
Numerical data
Logical arrays
Character arrays/variables
Table arrays
Cell arrays
Structure arrays
Function handles
Classes and graphic handles
While demonstrating how to generate these arrays, all of the created variable/arrays types will be preserved until the end of this section. Therefore, all variables/arrays are created once and preserved from the examples. Note that in some of the examples that generate random matrices, we employ MATLAB’s random number generators, which will create different random numbers every time they are called. However, in order to have permanent random values for variables and arrays, we have to set up the seed value of the random number generator rng(). With the fixed seed value, the random number generators (rand(), randi(), randn(), and so forth) will generate permanent/fixed random values every time they are called.
Numerical Data/Arrays
Note that I have set up the seed value of the random number generator in order to generate the permanent values from the random number generators rand(), randn(), and randi().
Note in these examples that the colon is one of the essential operators in managing and manipulating matrix and array elements. For example, NewDr(2, :) is equivalent to NewDr(2, 1:end). Both select all elements along row 2. Likewise, NewDr(:,:) is equal to NewDr(1:end, 1:end). They both select all elements starting from the first one, up to the last one.
These are a few examples of creating arrays in the Command Window. As stated, numerical arrays can be imported from other data files, such as *.dat, *.txt, *.xls, *.xlsx, and *.csv, as well as image files, such as *.jpg/jpeg, *.tiff, *.png, etc.
NaN (Not-a-Number)
Sometimes, you may need to remove NaN from your data. For instance, say you are analyzing measured data with some missing points (NaN). You need to remove the NaN from the data. How do you address this problem?
This answer is correct. This approach is quite straightforward, but with very large data sets, it will become tedious and time consuming or might even be impossible.
Note
You can assign new values to selected elements/components of arrays element by element or all at once by specifying the indexes (e.g., A_var([7 9 21)=[0 0 0]) of the elements/components.
Moreover, there are several other MATLAB functions that compute mean values, standard deviations, covariance values , etc., of numerical data arrays with NaN elements.
Note
You can use the following MATLAB functions to compute maximum, mean, median, minimum, standard deviation, and variance values of a numerical array containing NaN elements: nanmax(), nanmean(), nanmedian(), nanmin(), nanstd(), and nanvar(). They work by ignoring all of the NaN elements in the given array.
Here, the isnan() function identifies which elements of A_var are NaN and which ones are not. The new logical array called Index contains 1s and 0s. The 1s represent NaN elements and the 0s represent all other numerical elements.
Note
Logical indexing is a very powerful and efficient tool in identifying certain elements of numerical data sets/arrays/matrices according to their values and then assigning them new values.
Character Types of Variables
Note that these variables are kept and used in the coming sections to generate logical, table, cell, and structure types of array variables.
Function Handle
Function_handle_name =@MYfunction
Function_handle_name=@(variable1, variable2, ...)([expression1, expression2, ...])
Where MY_function is a function file, function expression, or another function handle.
Here the function handle called F1 calls the function file called MY_function.m and executes it with the user-specified input data for the a, b, and c variables.
f(x, a1, a2, a3 ) = a1x2 + a2x + a3;
Broader applications and uses of function handles are discussed in other chapters of the book—in Chapter 2, “Programming Essentials,” and Chapter 8, “Ordinary Differential Equations”.
Logical Arrays
Note that we set the seed value of the random number generator rng() in order to generate permanent element values with the uniform random number generator rand().
More uses/examples of logical arrays and indexing are discussed in other sections of the book.
Table Arrays
It is also possible to convert Table Arrays into arrays and cell arrays by using the tabel2array() and table2cell() commands , respectively. Understanding and working with Table Arrays will be of great help not only when you’re preparing reports but also when you’re importing data using the Import wizard and manipulating various data sets from external files (e.g. .txt, .xls, .dat, etc.) into the MATLAB workspace.
Cell Arrays
Cell arrays are useful for accommodating various types of arrays (numerical, character, logical, table, and function handle) in different cells of one cell type variable by preserving all attributes of each variable, unchanged. They might be very handy to carry or pass various data sets inside one variable. The cell arrays contain indexed data containers—cells accommodating lists of text, character strings, combinations of text and numerical data, and numerical arrays, function handles, structure arrays, and tables. One of the most essential features of cell arrays is that they require curly brackets to be used in specifying cell addresses. Another important feature of cell arrays is that data read by MATLAB will be in cell array mode.
You can change the contents of the cell array by double-clicking in each cell and entering the new values.
Structure Arrays
Structure arrays can accommodate all of the previously created array and entry (variable) types, namely, all types of numeric, logical, character, table, cell, and function handles. They can store data not only of different types but also of different sizes. One of the more important aspects of structure arrays is that they are suitable to code generation. Moreover, they are very useful in programming, data processing, data acquisition, and reading from Simulink models.
From the attributes of the variables in the workspace (see Figure 1-12), you can determine the variable type (scalar, array, logical, table, cell, structure, character, or function handle) and its storage type (double, single, uint8, or int8). Moreover, the symbols representing each variable shown in Figure 1-15 demonstrate some of the MATLAB supported data (array) sets shown in Figure 1-9.
It must be noted that many of these arrays can be converted from one type to another, as you have seen in some of the examples . For example, a cell array can be converted into a table array via the cell2table() function or similarly, a structure array can be converted into a table array via struct2table(). A table array can be converted into a cell and table array via table2cell() and table2struct(), respectively.
Complex Numbers
Two letters—i and j or 1i and 1j—are reserved for notating imaginary numbers. Therefore, it is advised not to use these letters to assign variable names. An alternative approach to assigning numbers is to multiply them by sqrt(-1).
Precision
MATLAB’s precision is not absolute.
In these expressions, t is a time vector containing a row of elements, such as [0, π/50, … 2π]. Some values of F are zero and some are non-zero, even though they are very small numbers. The reason for this is that all of the trigonometric functions, including exponential and logarithmic functions, are approximated by a polynomial of degree 13 with only odd powers of the argument variable (in this example, t). For instance, sin(t) ≈ t − c1t3 + c2t5 + … + c6t13 = p(t). The computation algorithm for all of these functions is implemented based on fdlibm, a “Freely Distributable Math Library” developed by at Sun Microsystems by K. C. Ng and others (for more information, see www.netlib.org/fdlibm).
The allocated data storage int8 can hold up to 28 − 1 integer numbers. All MATLAB supported data storage types are shown in Figure 1-15.
M-File and MLX–File Editors
In the context of this book, the terms code, script, and program are used interchangeably to refer to the M-files with the extension of *.m and MLX-files with the extension *.mlx, including function and executable files. Because of their extensions, these files are called M-files and MLX-files. In the previous examples, all of the operations and work are done in the Command Window. However, for programming and writing, editing and debugging, M-file and MLX-file editors will be of great help due to their helpful tools and hints in writing fast and more efficient codes/scripts/programs.
The overall functionality of M-files and MLX-files is similar except for one important feature. The MLX file editor window can display the outputs of calculations/simulations within the MLX editor window and indicate the most common command syntax related errors on its left-side output window. The M-file editor shows all errors in the Command Window after the M-file’s execution. Moreover, the MLX-file editor can interactively show all inserted equations via the equation editor; inserted images and hyperlinked texts are right in the same window. The outputs from the both files will be shown in the workspace. Both files can be used interchangeably. Let’s start reviewing M-file and MLX-file Editor windows and tools.
M-File Editor
The M-file editor window menu and GUI tools are sub-grouped in three tabs—EDITOR, PUBLISH, and VIEW, as shown in Figures 1-16, 1-17, and 1-18. Note that there are three main menu sub-groupings—HOME, PLOTS, and APPS—which belong to the main MATLAB window and were shown in initial sections.>
MLX-File Editor
M-files and MLX-files can be created in several different ways—by using GUI buttons or or by typing the command in the Command Window.
In order to demonstrate some of the highlighted tools and options of the M-file and MLX-file editors, let’s look at the following example to demonstrate that MATLAB’s precision is not absolute via the Pythagorean Theorem.
Example:
First, the solution script of this simple example will created in the M-file editor and the results will be published. Subsequently, all of the simulations will be carried out within the MLX-editor to demonstrate similar and different features of the both editors.
- 1.
Insert some comments describing the given problem statement.
- 2.
Define the input variable: .
- 3.
Perform the computation: F(α) = 1 − (sin2α + cos2α).
- 4.
Define for which values of the input variable α the function values of F(α) = 0.
- 5.
Plot the simulation results: α vs. F(α).
- 6.
Publish all of the obtained results, including the whole script.
Note that in this script, we used % to insert comments (non-executable information) and to insert and display Greek letters.
% Comments
Comments are not executable and contain additional information for the users. The % sign is used to place comments and remarks or any additional information within M-files and MLX-files. The comments can be added on a separate line or after the command syntax as long as they start with %. Using a double sign (%%) followed by a space automatically makes the following comments bold. Moreover, inserting %% at the beginning of a line and leaving a blank space after it creates a cell mode in the script. We discuss in detail the cell mode options and advantages in Chapter 2. Note that there are several other functionalities of the % sign. It is used to format specifications for write, display, read purposes, which we discuss in Chapter 2.
This is slightly edited with the PUBLISH tools, such as bold for Steps 1, 2, ..6) under INSERT INLINE MARKUP and Publish (PUBLISH); see Figure 1-17. Note that to make selected lines of comments bold, you first select the line and then press the button. Note that in this script, we used the LaTEX commands to insert the Greek letters (α, π) and the equation F = 1 − (sin2α+cos2 α).
The M/MLX editors are compatible with most common LaTEX mathematical mode commands. The LaTEX compatible mathematical commands and symbols can be inserted for plot titles, axis labels, graphic notes, and so forth, which are discussed in examples in the following chapters (programming, plots, and ODEs). For example, to insert the expression: x2 + y2 = R2, you enter the expression: x^2+y^2=R^2. Or to insert α, β, Ω, Ψ, you type alpha, eta, Omega, Psi. Moreover, to insert the equations with Greek letters, the notations need to start with $$ signs and end with $ (See Step 1. Problem statement and Step 5. Plot …). For more information and help with various mathematical expressions and symbols to write in LaTEX math, type the following in the command window: >> doc latex
Note that the bold lines (Figure 1-19), which are the starting lines of cell modes preceded with %%, have been recognized by the M-file editor automatically and put in contents and hyperlinked, such as % Step 1 ... Step 2 ... Step 6.
and press Enter, MATLAB automatically creates this bolded text header:
Step 2. Define the input variable.
Save the file as an *.mlx file (e.g., P2.mlx). Insert the mathematical expressions with the Equation tools under the INSERT sub-tab (shown in Figure 1-20) and by using . When you press the button, the whole range of symbols, structures, and matrices will be opened as shown in the following image.
Note that in the MLX editor, all of the executable and non-executable lines of the script are identified automatically and placed in separate sections. There are other salient issues about hints, warnings, and error messages from the M/MLX editors that we discuss in Chapter 2.
Closing the MATLAB Window
Quitting MATLAB is quite simple. There are several commands that can be used to complete the work in MATLAB and close down all its windows. You can type >> quit or >> exit or use the keyboard shortcut Ctrl+Q. You can also click the X in the upper-left corner of the main MATLAB window or call the >> finishdlg function from the Command Window.
Note that all variables residing in the workspace will be cleared upon exiting/quitting MATLAB. They will be lost and not be recovered by default the next time MATLAB is started. However, they can be saved to a *.mat file and loaded back to the workspace. The command history of entered commands is saved automatically and all of the entered commands in the Command Window can be accessed the next time you launch MATLAB. If you’re interested in changing the number of commands that can be adjusted via MATLAB preferences, choose Preferences ➤ Command History.
Summary
This chapter introduced the MATLAB environment, including its settings, variables, common commands, and M-file/MLX-file GUI tools. You also learned about assigning variables and values from the Command Window and working in the M/MLX-file editor windows. In addition, the chapter explored data types, formats, and structures and covered how to use built-in MATLAB commands and functions. In particular, it covered help search options and most commonly used commands, including help, helpwin, helpbrowser, doc, lookfor, clear, clear all, dir, pwd, cd, ls, save, load, clearvars, edit, format, char, size, who, whos, input, what, and exit/quit.
References
- [1]
- [2]
- [3]
- [4]
- [5]
- [6]
Exercises for Self-Testing
Exercise 1
- 1.
Find the Vibrating Logo demo from the pre-installed MATLAB demos and run it. Hint: membrane.
- 2.
Locate Product Overview from the package’s Help Library.
- 3.
Change the font type and size of the Command Window.
Exercise 2
- 1.
Use the Help Library to determine how to add a new path for search. Add a new path for search: C:UsersPublic. Hint: addpath.
- 2.
Use the MATLAB help browser to find out how to create a new directory. Create a new directory called my_new_dir inside the C:UsersPublic directory. Hint: mkdir.
Exercise 3
Get help with the MATLAB exp (exponential) function using the Command Window. Use the help, lookfor, doc, and help browser commands and then compare the results of the four help options.
Exercise 4
Create and open an *.m file called learn.m in M-file editor window using the Command Window. (Hint: >> edit ...). Insert two commands in it that display the current date and time. Hint: date, clock.
Exercise 5
Create a shortcut (a set of favorite commands) that opens a new M-file named My_Shortcut and simultaneously closes all figure windows and clears the Command Window and Workspace from all previously entered data and commands.
Exercise 6
Change from the Preferences window a display of data formats using the Command Window. Make it hexadecimal format. Hint: format.
Exercise 7
Which commands are used to clean up the Workspace, Command Window, and History?
Exercise 8
Use the Array Editor to change the assigned values for x, y and z and re-execute the expressions to compute A and B.
Exercise 9
- a)
Your program should contain an input variable that is the length of a square side as a variable parameter in meters.
- b)
Your program should calculate the area of a square and the volume of a cube.
- c)
Your program should output the calculated results (area and volume) in the metric (m2, m3) and British (in2, in3) systems by using conversion, e.g., 1 inch = 25.4 mm.
- d)
Execute your script (my_first_program.m) from the Command Window.
- e)
Execute your script (my_first_program.m) from the M-file Editor Window.
Exercise 10
Which command displays what is stored in your MATLAB workspace?
Create and save it in uint64 format.
Why is the value of P in uint64 equal to 1? How do you fix this issue?
Exercise 11
Save all computation results from Exercises 9 and 10 in a MAT file called my_FIRSTwork.mat and clean up your MATLAB workspace, removing all variables except for A and B from Exercise 8.
Exercise 12
Exercise 13
- 1.
Change display data formats for the Command Window and make it a long e.
- 2.
Where are the preferences settings of MATLAB saved?
- 3.
What is the main function of the M-file finishdlg.m and what commands does it contain?
Exercise 14
- 1.
Write a command in the Command Window that creates and opens an M-file called Ex14.m.
- 2.
Edit your M-file Ex14.m so that it contains a command that changes the display format type.
- 3.
Edit your M-file Ex14.m so that it contains a command that changes the current directory.
- 4.
Edit your M-file Ex14.m so that it contains a command that displays the current date and time.
Exercise 15
Why is day_DUE numeric and equal to a 10-element row matrix?
What do these numbers represent?
Exercise 16
Given: >> A=[1,2; -12.0, 3]; mat2str(A); SNA=ans+0; char(SNA)
What is hidden behind the variable SNA?
Exercise 17
- 1.
Create a cell called Matlab that is composed of two sub-cells: {'Day#1', 'Start'}
- 2.
Create a numeric array called classes that contains elements []. Note that i represents an imaginary number.
Exercise 18
Create a function handle and inline function of the following mathematical expression:
h(θ, t) = 1.3 * e−tiθ. Note that i represents an imaginary number.
Exercise 19
It is analytically proven that cos2α = 2 cos2α − 1. Use MATLAB to compute the equality for different values [] of α and define the values of α in which the accuracy of MATLAB calculations does not represent equality.
Exercise 20
Use MATLAB to compute the expression in a most accurate way. Note that it is in a fifth root.
Exercise 21
How do you fix this problem and make the results legible?
Exercise 22
Create a 5-by-5 matrix called A by using randi() within [1, 20] divided by 3. Display A as rational numbers, as shown here. Note that your array numbers (in the numerator) of A will differ from the ones shown here. Why does your answer differ from the one shown here?
Exercise 23
Create the following array in the most efficient way (at least two different ways). Note the display format of the A2 elements.
Exercise 24
Using randi(), create a 15 by 15 array with elements ranging from -125 to 127 and save it in the most memory-efficient way with the name A3.
Exercise 25
Create the following HTML report using M-file editor tools.
Exercise 26
- 1.
Obtain B5 from A5 using two arithmetic operations: B5 = [16, 9 4; 1 0 1; 4 9 16].
- 2.
Obtain C5 from A5 and B5 by using relational logic (<, >) and arithmetic operations (+ 13).
Exercise 27
Create three numerical (row matrix) arrays (variables called AJ, IS, and LJ) so that, when you subtract three from each and then perform one conversion operation, you obtain Al-Khwarizmi, Ibn Sina, and Lennart Johansson.
Exercise 28
Save all of your created variables (A, A2, A3, A4, A5, and A6) from Exercises 22-27 in a *.mat file with your last name, e.g. Jones_HW2.mat.
Exercise 29
Create a cell array (called A) containing three variables: a=4/5, b='matlab'+0, and c=sin(π), and create a structure (called B) containing four variables: a, b, c, and A. Show how you access the a, b, and c variables residing inside A and B.
Exercise 30
Create the following variables and entries in the MLX File Editor:
Function handle F: F(ω1, ω2, θ) = cos (ω1θ) − sin (ω2θ)
Identity matrix:
Magic numbers:
Multiply the matrix by 2 and subtract it from the M matrix. Call the new matrix MI:
Exercise 31
Explain how to obtain the following Layout (1), Preferences (2), and Quick Access (3) windows, as shown in the screenshots. Note: Fonts and Colors in (2).
Exercise 32
Create these files (MLX/M-files) and explain how to display the results as shown in the figure in the Live Editor window.
Note that there are four windows displaying MLX and M-files; Equations, Greek letters, Plot figures, hyperlinks, data tips, and how to insert an image.
Exercise 33
- 1.
MATLAB’s default numerical format (int8, uint8, int16, uint16, … single, or double) depends on the operating system on which MATLAB is installed. (True/False)
- 2.
Where does MATLAB display a list of stored variables and associated attributes?
- 3.
The MATLAB user interface is customizable. (True/False)
- 4.
MATLAB supports cell arrays only if they are numerical data, not strings. (True/False)
- 5.
It is possible to put a table array variable into a cell array. (True/False)
- 6.
A=1.1; B=[2, 3; 1 2]; C=B/A; format hex; C
We are changing the values of entries C by changing the display format. (True/False)
- 7.
>> D=uint8(255); D=255; D+1 =255; E = [12/14, 3/5; 1/3, 4/9]; format rat; E
We have changed the values of entries D and E by changing the display format. (True/False)
Exercise 34
- 1.
Given a cell array ABBA with 10 cells, which command will recall the elements residing in cell 3 of ABBA?
- 2.
Given a 5-by-5 array (matrix) called A, A(4:end, 3:4), it will produce a matrix of what size?
- 3.
How do you create a linearly spaced data array: a=(-13, -12, -11, ... 11, 12, 13) and b=(0, 1/13, 2/13, 3/13, ... 24/13, 25/13, 2) without typing all the elements? Note how to obtain the rational format type of the array b.
Exercise 35
How do you get a logical array c = (1 1 1 1 1 0 0 0 0 0 0) from the array a = (-5, -4, -3 ... 3, 4, 5) whose elements are linear (equally spaced)?
Exercise 36
There are errors. Find errors and fix them. What is the size of x and F now?
Exercise 37
- 1.
How do you change a working directory to: C:UsersPublic and add this path for searching?
- 2.
Create a new directory called MYdir inside the C:UsersPublic directory.
- 3.
How do you find out which variables are stored in your MATLAB workspace?
Exercise 38
- 1.
Change the last two columns (column 8 and 9) of D2 (D2=zeros(9); D2(6,:)=1:9;) given above to have the elements: [e0, e1, e2, …, e8] and [ tan(e0), tan(e1), tan(e2), …, tan(e8)], respectively in the most efficient way.
- 2.
Generate these vector spaces in two different ways: [-100, -90, -80, ... 100], [-100, -99, -98, ... 100].
- 3.
How do you generate 500 data points equally spaced within −π. . π ]?
Exercise 39
- 1.
Given >> A=magic(3); C1=le(A,7), C2=A<=7
What do 0 and 1 mean in all logical arrays for each individual case?
- 2.
Given >> A1=12.12; C="nan"; B=[1 2; 0, 3i]; D=B/0; AA1=isfinite(A1), CC1=isnan©, DD1=isinf(D), DD2=isnan(D)
What do 0 and 1 mean in all logical arrays for each individual case?
- 3.
Given >> AG=randi([-13, 25], 3, 2); BAG=(AG>0 & AG<13)
Why do your answers differ when you run these commands to define AG and BAG?
- 4.
Given >> GAB=find(AG>0 & AG<13), AG(GAB)
What numbers are behind GAB and how are they related to AG?
- 5.
Given >> 13>10; -1.2<=7.8; -11+13>=3
Why are we getting 0s and 1s?
- 6.
Given >> AA=randi([-13, 13], 10, 2); AA(AA<=0); % OR >> IN=(AA<=0); AA(find(IN));
What does IN represent with reference to [AA]?
- 7.
Given >>B = randi([0, 13], 5); k=find(B>=3 & B<=5)
Which numbers are in k with reference to B?
Exercise 40
- 1.
Write the command to clean up the workspace and Command Window of MATLAB, and display the current date and time in the Command Window.
- 2.
Create array A and write commands to generate arrays: A1 (1-by-10) with the operator : A2 (10-by-1) with linspace(), A3 (2-by-10) with eye().
- 3.
Create array B and write commands to create arrays: B1 (5-by-6) with randi() elements ranging between [-1….1], B2 (5-by-6) with rand(), and B3 (5-by-10) with randn().
- 4.
Create array C and write the commands to generate arrays: C1 (5-by-10) with magic() and repmat(), C2 (6-by-10) with eye(), and C3 (10-by-10) with ones().
- 5.
Write the commands to perform all possible (arithmetic array) operations (+, -, , /, ., ./, ^, and .^) with A1, A2, and A3 (at least three operations) and call new matrices: A1new1, A1new2, A1new3, A2new1, A2new2, A2new3, A3new1, A3new2, and A3new3. Hints: use transpose() and rot90() while performing arithmetic array operations.
- 6.
Write the commands that perform all possible (arithmetic array) operations (+, -, , /, ^, ., ./, , sum, and mean) with B1, B2, and B3 (at least three operations) and call new matrices: B1new1, B1new2, B1new3, B2new1, B2new2, B2new3, B3new1, B3new2, and B3new3. Hint: Use fliplr() while performing arithmetic array operations.
- 7.
Create AB1, AB2, and AB3 matrices from A1, A2, A3, and B1, B2, and B3. Also, use part of any the A1, A2, A3 and B1, B2, B3 arrays. Note that every AB1, AB2, AB3, ABC4, and ABC5 array should contain some elements from arrays A and B. Hint: Use flipud() and repmat() while creating the arrays AB1, AB2, and AB3.
- 8.
Create ABC1, ABC2, and ABC3 matrices by combining/concatenating the previously created arrays: A1, A2, A3 and B1, B2, B3 and C1, C2, C3. You should also use part of any A1, A2, A3 and B1, B2, B3 and C1, C2, C3 arrays. Note that every ABC1, ABC2, ABC3 array should contain some elements from A, B, and C matrices from Parts 1, 2, and 3.
Exercise 41
- 1.
The command that creates a cell array called Q1 with six empty column cells.
- 2.
The command that gives binary representations of 12321 and 987654321, and a command writing these numbers, including their binary representations in cells 1, 2, 3, and 4 of Q1, respectively.
- 3.
The command that converts the binary representations of 12321 and 987654321 into numerical arrays by using MATLAB’s conversion commands—str2num( ) or str2double( )—and the command that writes the two converted numerical arrays in cells 5 and 6 of Q1, respectively.
- 4.
The command that generates the following array using pascal() (a MATLAB built-in matrix function):
And by applying logical indexing (logical array) and element-wise matrix multiplication operations, generate the following array:
- 5.
The command that creates a structure array called S5 and the command that writes its Q1, H, and HLG.
- 6.
Explain why the converted numbers (in Step 3) of the binary representations (of 12321 and 987654321) differ from the original decimal numbers, i.e. 12321 and 987654321?
Exercise 42
- 1.
Generate two column arrays with 202 equally spaced data points in two ways: = −2π…2π; β = −3600…3600.
- 2.
Compute these three equations (take the values of α, β from Step 1): F(α) = esin(α); H(β) = ecos(β); S = 1 − (sin2α + cos2 β). Note: β is given in degrees not in radians and thus, do not forget to convert it into radians. Also, insert the equations by using the equation editor of *.mlx.
- 3.
Create an array (called Solution) of five columns containing: α, F(α), β, H(β), S
- 4.
Create a table of arrays. The table of variables should be called TVall and has to be in the following format.
- 5.
Find all of the positive values of F, S, and H, and the corresponding α, β values and save all of them in a cell array variable called FSH_pos.
- 6.
Find all the absolute zero values of S and the corresponding α, β values. Save them in an array called ABS_0 with three columns of the found S α, β values.
- 7.
Create a structure of arrays called ABFSH_struct containing: SOLUTION, TVall, FSH_pos, and ABS_0 from Steps 3, 4, 5, and 6.
- 8.
Clear all the variables in the workspace except for α, β, F, H, S, SOLUTION, TVall, FSH_pos, and ABFSH_struct from the previous steps. Save these variables in an *.mat file called Ex42.mat.
Exercise 43
- 1.
Clears the workspace and Command Window from all entries.
- 2.
Closes all open figure windows.
- 3.
Creates a new directory called C:DocumentsEx43.
- 4.
Changes the current directory of MATLAB to a newly created directory: C:DocumentsEx43.
- 5.
Computes t = [0, 3π] with ∆t = π/200, ,
- 6.
Saves the computation results (t f1(t), f2(t)) in a .mat file called Ex43.mat.
Exercise 44
- 1.
Changes the current directory of MATLAB to the MATLAB’s root directory (Hint: matlabroot).
- 2.
Removes the directory created in Exercise 43: C:DocumentsEx43.
- 3.
Displays the MATLAB’s root directory in the Command Window.
- 4.
Creates two function handles: and .
- 5.
Saves the current path and the function handles in a structure array called EX44.