© Sulaymon Eshkabilov 2019
S. EshkabilovBeginning MATLAB and Simulinkhttps://doi.org/10.1007/978-1-4842-5061-7_1

1. Introduction to MATLAB

Sulaymon Eshkabilov1 
(1)
Fargo, United States
 

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 ../images/471979_1_En_1_Chapter/471979_1_En_1_Figa_HTML.jpg icon/shortcut from the desktop window or choosing Start ➤ All Programs ➤ ../images/471979_1_En_1_Chapter/471979_1_En_1_Figb_HTML.jpg. 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.

This main desktop window is shown in Figure 1-1.
../images/471979_1_En_1_Chapter/471979_1_En_1_Fig1_HTML.jpg
Figure 1-1

Default MATLAB desktop window (R2018b)

The main components of the package’s graphical user interface (GUI) tools are as follows:
  • 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 ../images/471979_1_En_1_Chapter/471979_1_En_1_Figc_HTML.jpg. By clicking on ../images/471979_1_En_1_Chapter/471979_1_En_1_Figd_HTML.jpg (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.

../images/471979_1_En_1_Chapter/471979_1_En_1_Fig2_HTML.jpg
Figure 1-2

MATLAB main menu: The HOME, PLOTS, and APPS tabs (MATLAB R2018b)

One of the most essential strengths of this package is its help documentation, which includes help libraries and tools. They can be accessed using GUI tools and entries from the Command Window. It is a good idea to start using the package by exploring the Getting Started options, which you can access by clicking the Getting Started hyperlinked text, above the Command Window. This brings up the Help Library documentation, as shown in Figure 1-3, which contains the essential documentation and help tools, such as examples and function syntax.
../images/471979_1_En_1_Chapter/471979_1_En_1_Fig3_HTML.jpg
Figure 1-3

Getting Started with MATLAB and Help Library documentation

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.

There are a few other hands-on ways to obtain help. For example, to get quick help about MATLAB’s built-in function tools and commands, including user-generated functions, users can type the following in the Command Window:
>> doc size;       % extended help on the command SIZE
>> helpwin size;   % help shown in a separate window on the command SIZE
>> help clear      % quick help on how to use the command CLEAR
>> help matrix;    % quick help how to use the command ISMATRIX
>> help +          % quick help on "+"
>> help size;      % quick help on SIZE
>> lookfor size    % extensive search for a list of functions and files containing  the command SIZE.
Figure 1-4 and Figure 1-5 show some of the results of quick and extensive help. In addition, the application has GUI tools and broad online library resources, product descriptions, video tutorials, and open public forums on the MathWorks website.
../images/471979_1_En_1_Chapter/471979_1_En_1_Fig4_HTML.jpg
Figure 1-4

Getting help

../images/471979_1_En_1_Chapter/471979_1_En_1_Fig5_HTML.jpg
Figure 1-5

Getting help

You can search for help in MATLAB using the Command Window and the help, lookfor, doc, docsearch, and helpwin commands for the clock function , for example:
  1. 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. 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. 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. 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. 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. 6.

    You can use the F1 keyboard key to open the Help Library and documentation.

     
  7. 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

Let’s start working with the MATLAB environment by making some changes to its layout using its GUI tools, such as Layout, Preferences, and Set Path, which are located on the HOME tab. To make changes to the layout (see Figure 1-6) from the HOME tab’s main menu, you have to click on the Layout drop-down menu (1). Many options and different windows are available to choose from. The Desktop window consists of Command, Command History, Current Directory, and Workspace windows if there are tick marks before those window names. You can separate or drag around any of these windows by clicking the title bar and dragging the window to the new location.
../images/471979_1_En_1_Chapter/471979_1_En_1_Fig6_HTML.jpg
Figure 1-6

Changes in Layout (1) and Preferences (2)

To make changes to the Preferences window, you either click on ../images/471979_1_En_1_Chapter/471979_1_En_1_Fige_HTML.jpg from the main menu or type the following in the Command Window and press Enter:
>> preferences

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.

You can modify many options/tools, including the GUI quick access tools and Editor/Command window displays, from the Preferences window. To display the tips and highlight the current line in the Editor window, for example, you choose Preferences ➤ Editor/Debugger ➤ Display and then check Enable Data-Tips in Edit Mode. Many tools can be added to the main menu as shortcuts. Some of these key customizations in Preferences can also be attained by issuing commands from the Command Window.
../images/471979_1_En_1_Chapter/471979_1_En_1_Fig7_HTML.jpg
Figure 1-7

Setting a path (3), adding a folder, and removing a path

Working in the Command Window

Work in MATLAB generally starts in the Command Window, but before you type any command, it is worth noting the current directory. The current directory address can be viewed directly from the main window (see Figure 1-8) or by typing this command in the Command Window:
>> pwd
If required, you can change the current directory using the >> cd command or by clicking on the path’s directory (see Figure 1-8) with left mouse button and typing the directory address (C: ➤ Users ➤ David ➤ Documents ➤ MATLAB ➤).
../images/471979_1_En_1_Chapter/471979_1_En_1_Fig8_HTML.jpg
Figure 1-8

Viewing and changing the current working directory

In addition, you can add a few new paths to work within the working directory. For instance, to add a path to an existing folder, use the following.
>> addpath('C:UsersDavidDocumentsMATLAB');

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

Variable names must start with a letter and can be combined with any integer numbers, such as 0, 1, 2, … 9 and (_) an underscore sign. No other symbols can be used for variable names. The maximum length of the variable name is 63 characters. MATLAB treats the variables called a and A as two different variables because of its ANSI/ASCII symbol conversions. Now let’s get started working in the Command Window by entering and assigning variable names, performing simple some basic arithmetic operations, and making changes to the output data formats.
>> A=3; B=-2; C=1/2; D = -1.5; ABCD=A^2+B/C+D;
>> ABCD              % ";" is missed and the content of the variable ABCD is displayed
ABCD =
  3.5000
>> sqrt(ABCD)  % if a variable name is not assigned, "ans" is a default name by MATLAB
ans =
    1.8708
>> ans+1  % if a variable name is not assigned, "ans" will substitute the previous "ans".
ans =
   2.8708
The results of user entries are displayed in the Command Window and can be altered using these display format options: format long, format short, format long eng, format bank, format hexadecimal, format rational, etc. Here are some examples of format options. When you change the display format types, the actual variable values do not change.
>> A=3; B=-2; C=1/2; D = -1.5;
>> ABCD=A^2+B/C+D;
>> format bank
>> ABCD
ABCD =
          3.50
>> format long eng
>> ABCD
ABCD =
    3.50000000000000e+000
>> sqrt(ABCD)
ans =
    1.87082869338697e+000
>> format short
>> sqrt(ABCD)
ans =
    1.8708
>> format bank
>> sqrt(ABCD)
ans =
          1.87
>> format long eng
>> sqrt(ABCD)
ans =
    1.87082869338697e+000
>> format compact
>> sqrt(ABCD)
ans =
    1.87082869338697e+000
>> format rat
>> sqrt(ABCD)
ans =
    1738/929
>> format hex
>> sqrt(ABCD)
ans =
   3ffdeeea11683f49

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.

The three most commonly used commands for housekeeping in MATLAB are:
  • 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

All of these commands can also be used with M-files and MLX-files. It must be noted that the clear all command is not recommended with M-files and MLX-files, because it will decrease the efficiency of code/script and create unwanted behaviors when you declare the clear global command. Let’s look at some ways to employ these commands efficiently.
>> A=3; B=-2; C=1/2; D = -1.5; ABCD=A^2+B/C+D;
>> clear         % Removes all of the entries in the workspace and workspace becomes all blank
>> clearvars       % The same as "clear"
>> clear variables % The same as "clearvars"
>> clear all % The same as "clear" and also removes already compiled codes as well
>> clear  A B C D  % Removes variables: A B C D and leaves ABCD untouched
>> A=3; B=-2; C=1/2; D = -1.5; ABCD=A^2+B/C+D;
>> clearvars  –except A B C   % Removes all variables except for: A B C
MATLAB can use a wildcard * asterisk for variables and filenames. For example, to remove all variables whose names start with the letter “A”, you would use the following command.
>> A=3; B=-2; C=1/2; D = -1.5; ABCD=A^2+B/C+D; ABC=A^2+B*C;
>> clear  A*    % Removes all variables staring with A, i.e. A, ABCD and ABC are removed
>> clearvars A*  % The same as: clear A*
All entered and saved variables can be viewed from the workspace window by typing the who or whos command in the Command Window. For example:
 >> A=3; B=-2; C=1/2; D = -1.5; ABCD=A^2+B/C+D; ABC=A^2+B*C;
>> who
  A  B  C  D  ABCD  ABC
>> whos
Name      Size            Bytes  Class     Attributes
  A       1x1                 8  double
  ABC     1x1                 8  double
  ABCD    1x1                 8  double
  B       1x1                 8  double
  C       1x1                 8  double
  D       1x1                 8  double

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.

Table 1-1

Data Storage Format Types in MATLAB

-../images/471979_1_En_1_Chapter/471979_1_En_1_Figf_HTML.gif

When you have numerical data and a floating point format, the double precision storage gives you the largest storage space for higher accuracy. Double precision can save up to 16 decimal digits. The single precision storage for floating point-formatted data is more memory efficient and less accurate than the double precision, which is the default storage format in MATLAB. If only integers are used in your calculations and data processing, it is more appropriate to use int8…64 or uint8 … 64, depending on the largest value of your data. Here are some examples of how to specify storage type while saving the values of the declared variables.
>> F01=127;Fint_08=int8(F01), Fnew1 = Fint_08+1
Fint_08 =
 int8
 127
Fnew =
 int8
 127
>> F16=65535; Fint_16=uint16(F16), Fnew2 = Fint_16+1
Fint_16 =
 uint16
 65535
Fnew2 =
 uint16
 65535
In calculations of the Fnew1 and Fnew2 variables from the int8 and uint16 formatted variable values, the allocated storage space cannot accommodate any more values (i.e., for int8 maximum allocated storage space is 127 = 27 − 1 and for uint16 it is 65535 = 216 − 1). Therefore, errors in the calculations have taken place. Note that in such cases, MATLAB does not show an error. Figure 1-9 shows all the data storage types and data formats supported in MATLAB.
../images/471979_1_En_1_Chapter/471979_1_En_1_Fig9_HTML.png
Figure 1-9

Different types of data storage options supported 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.

Finally, to exit from MATLAB or quit a work session, issue one of these commands from the Command Window:
>> exit
>> quit

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

Use the Command Window in these instances:
  • 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

Let’s look at several examples to show other operations you can perform in the Command Window.
  1. 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 workspace
    Undefined 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-sensitive
    Undefined 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 2
    Error using vertcat
    Dimensions 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 shown
    Dot indexing is not supported for variables of this type.
    >> BCF = [B, C, F16] % This is the anticipated correct command.
     
  2. 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. 3)
    To obtain quick help:
    >> help format
     format Set output format.
     format with no inputs sets the output format to the default appropriate
     for the class of the variable. For float variables, the default is
     format SHORT. ...
    >> help dir
     dir List directory.
     dir directory_name lists the files in a directory. Pathnames and
     asterisk wildcards may be used. A single asterisk in the path touching
    >> help what
     what 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 partial
     path, complete path, relative path, or no path. If ITEM includes a
     partial path or no path, ...
     
  4. 4)
    To view MATLAB compatible files:
    >> type QQQ.txt % Note: the file QQQ.txt was available in the current directory
    CY     bBb    88
    AH     AAAA+  98
    CWW    AAAA+  98
    ...
    >> type MYfile.mlx % Note: the file MYfile.mlx was available in the current directory
    N=13;
    M=randi(N,9);
    stairs(M, 'bd-')
    >> type myfun.m % Note: the file myfun.m was available in the current directory
    function f=myfun(x)
    f=[2*x(1)-x(2)-exp(-x(1));
     -x(1)+2*x(2)-exp(-x(2))];
    End
     
  5. 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. 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. 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 ../images/471979_1_En_1_Chapter/471979_1_En_1_Figg_HTML.jpg, delete them ../images/471979_1_En_1_Chapter/471979_1_En_1_Figh_HTML.jpg, or open them ../images/471979_1_En_1_Chapter/471979_1_En_1_Figi_HTML.jpg.

Similarly, you can create a MATLAB file with ../images/471979_1_En_1_Chapter/471979_1_En_1_Figj_HTML.jpg or an M-file with ../images/471979_1_En_1_Chapter/471979_1_En_1_Figk_HTML.jpg or open an existing MATLAB file with ../images/471979_1_En_1_Chapter/471979_1_En_1_Figl_HTML.jpg. You can delete the files via the right and left mouse button options. You can also view the current directory or change it using ../images/471979_1_En_1_Chapter/471979_1_En_1_Figm_HTML.jpg.

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.

As stated, MATLAB reads every entry (numerical and character types) as an array. If the storage type is not specified, the default storage type is always double. Let’s look at several examples of how to generate various data types supported in MATLAB:
  • Numerical data

  • Logical arrays

  • Character arrays/variables

  • Table arrays

  • Cell arrays

  • Structure arrays

  • Function handles

  • Classes and graphic handles

../images/471979_1_En_1_Chapter/471979_1_En_1_Fig10_HTML.jpg
Figure 1-10

Types of data (array) sets supported in MATLAB

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

There are many different ways to create and generate numerical arrays . For example, you can use direct entries from the Command Window by typing all the numerical values of an array and you can generate numerical entries using built-in functions and commands. Data can be imported from another file (.mat, .txt, .dat, .xls, .jpeg, .au, etc.) or generated using existing data or imported data in MATLAB. Data can also be computed using specific mathematical expressions and arithmetic/matrix operations.
>> format short      % To display numerical elements of arrays in a short format
>> A = 2; B = -3.25; C=(A+B)^2; % Entries and arithmetic operations.
>> ABC=[A, B, C] % Use of Existing Data: 1-by-3 array
ABC =
    2.0000   -3.2500    1.5625>> Drow=[1, 2, 3, -4] % Just entry: row array. Comma "," element separator in it.
Drow =
     1     2     3    -4>> Erow=[-2 -1 0 Drow] % Entry and Use of existing data: Row Array. Space is a separator.
Erow =
    -2    -1     0     1     2     3    -4>> Fcol=[1; 2; 3; -4] % Entry: Column Array. Elements are separated with ";".
Fcol =
     1
     2
     3
    -4>> DE = [2*Drow; (3/4)*Drow] % Use of Existing Data and arithmetic operations: 2-by-4 array
DE =
    2.0000    4.0000    6.0000   -8.0000
    0.7500    1.5000    2.2500   -3.0000
An alternative way to generate numerical arrays/data is to employ built-in array generator functions of MATLAB.
>> Aone=ones(2, 6) % 2-by-6 array generated with elements of 1
Aone =
     1     1     1     1     1     1
     1     1     1     1     1     1>> Bzero=zeros(5, 6) % 5-by-6 array generated with elements of 0
Bzero =
 0 0 0 0 0 0
 0 0 0 0 0 0
 0 0 0 0 0 0
 0 0 0 0 0 0
 0 0 0 0 0 0
>> Ceye=eye(6) % 6-by-6 eye matrix array generated
Ceye =
 1.00 0 0 0 0 0
 0 1.00 0 0 0 0
 0 0 1.00 0 0 0
 0 0 0 1.00 0 0
 0 0 0 0 1.00 0
 0 0 0 0 0 1.00
>> Seed = 1; rng(Seed);    % Seed value of the random number generator rng() is set up in order to              % generate fixed random numbers
>> Dr1 =rand(9, 5)     % 9-by-5 array of uniform distributed random numbers generated
Dr1 =
    0.4170    0.5388    0.1404    0.0391    0.6865
    0.7203    0.4192    0.1981    0.1698    0.8346
    0.0001    0.6852    0.8007    0.8781    0.0183
    0.3023    0.2045    0.9683    0.0983    0.7501
    0.1468    0.8781    0.3134    0.4211    0.9889
    0.0923    0.0274    0.6923    0.9579    0.7482
    0.1863    0.6705    0.8764    0.5332    0.2804
    0.3456    0.4173    0.8946    0.6919    0.7893
    0.3968    0.5587    0.0850    0.3155    0.1032>> Dr2 =randn(4, 6) % 4-by-6 array of normally distributed random numbers generated
Dr2 =
   -0.1551   -1.1714   -0.5581   -2.0187   -0.4852    0.0407
    0.6121   -0.6856   -0.0285    0.1997    0.5943    0.2830
   -1.0443    0.9262   -1.4763    0.4259   -0.2765    0.0636
   -0.3456   -1.4817    0.2589   -1.2700   -1.8576    0.4334>> Dr3 =randi([-5, 5], 5,5) % 5-by-5 array of integer numbers ranging between -5 ... 5
>> Dr3 =randi([-5, 5], 5,5)
Dr3 =
     1    -1     2    -3     1
     4    -4     4     4    -4
    -4     5     1    -1     5
    -4    -2     3     5    -1
     3     3    -2     2     1

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().

Moreover, there are many other standard matrix/array generators built into MATLAB, e.g. pascal(), krylov(), leslie(), cauchy(), clement(), lesp(), poisson(), neumann(), etc. To get help with these array generators, type the following in the Command Window:
>> help gallery
>> doc gallery
It must be noted that all of these generated numerical entries/arrays are saved in double precision format. Changing the storage format type of any these variables is quite simple and straightforward.
>> Dr3new=int8(Dr3) % Dr3new is Saved in int8
Dr3new =
  5×5 int8 matrix
    1   -1    2   -3    1
    4   -4    4    4   -4
   -4    5    1   -1    5
   -4   -2    3    5   -1
    3    3   -2    2    1>> Dr2new=single(Dr3) % Dr2new is Saved in a single precision
Dr2new =
  5×5 single matrix
     1    -1     2    -3     1
     4    -4     4     4    -4
    -4     5     1    -1     5
    -4    -2     3     5    -1
     3     3    -2     2     1>> A1New=uint8(Aone) % A1new is Saved in uint8
A1New =
  2×6 uint8 matrix
    1   1   1   1   1   1
    1   1   1   1   1   1
Now it is time to check the attributes/properties of the numerical entries created in the Command Window and saved in the workspace. You do this by using the whos command, as shown in Figure 1-11.
../images/471979_1_En_1_Chapter/471979_1_En_1_Fig11_HTML.jpg
Figure 1-11

Created numerical data types and variables residing in the workspace

The most used data type in MATLAB is the numerical array. Therefore, it is essential to learn how to work with arrays of different sizes (many rows and many columns). In order to work with arrays, you should understand how to properly locate addresses of array elements, rows, and columns. Arrays are read as rows by columns. For example, >> DE(2, 1) means we are taking the element of DE residing on the second row and the first column, i.e. 0.7500. Likewise, >> DE(1, 4) means we have selected the element of DE residing on the first row and fourth column, i.e. -8.
>> DE
DE =
    2.0000    4.0000    6.0000   -8.0000
    0.7500    1.5000    2.2500   -3.0000
>> DE(2,1)
ans =
    0.7500
>> DE(1,4)
ans =
    -8
Thus, an element in any array can be located with respect to its row and column. The colon operator : is used to select all elements along rows or columns or both. For example, >> DE(1,:) selects all elements residing in the first row of DE, i.e. [2, 4, 6 -8]. Likewise, DE(:, 3 ) selects all elements residing in the third column of DE, i.e., [6; 2.25].
>> DE(1,:)
ans =
     2     4     6    -8
>> DE(:,3)
ans =
    6.0000
    2.2500
You can use the colon operator to select all element of matrices or arrays, For example, >> DE(:, :) is the equivalent of DE. The end keyword enables you to select elements up to the last one. For example, >> DE(1, 1:end) is equivalent to >> DE(1, :).
>> DE(1, 1:end)
ans =
     2     4     6    -8
>> DE(1, :)
ans =
     2     4     6    -8
As another example of how to select elements of matrices, in Dr3new, the element residing in the second row and first column is 0. An alternative way to locate any element in any given array is by the order count. Elements in arrays are counted on a column basis. For example, the order of the element number 2 in Dr3new will be 0 and element number 6 in Dr3new is 2. Note that I used the random number generator to create Dr3new and thus, your Dr3new will differ. Again, let’s look at several examples of manipulating arrays based on Dr3new and Dr1.
>> Dr3new
Dr3new =
  5×5 int8 matrix
    3   -5    0    1   -3
    3   -5    1    5    3
    5   -5    4    1   -1
    2   -3   -4   -5    4
   -4    4   -2    3    3
>> Dr3new(2,1)
ans =
  int8
   3>> Dr3new(2)
ans =
  int8
   3>> Dr3new(6)
ans =
  int8
   -5>>  Dr3new(2,:)=0 % This makes a second row of elements equal to 0
Dr3new =
  5×5 int8 matrix
    3   -5    0    1   -3
    0    0    0    0    0
    5   -5    4    1   -1
    2   -3   -4   -5    4
   -4    4   -2    3    3>> Dr3new(:,5)=1 % This makes fifth column of elements equal to 1
Dr3new =
  5×5 int8 matrix
    3   -5    0    1    1
    0    0    0    0    1
    5   -5    4    1    1
    2   -3   -4   -5    1
   -4    4   -2    3    1>> Dr3new(end,:)=-5 % This makes the last row of elements equal to -5
Dr3new =
  5×5 int8 matrix
    3   -5    0    1    1
    0    0    0    0    1
    5   -5    4    1    1
    2   -3   -4   -5    1
   -5   -5   -5   -5   -5>> Dr2new(1:5, 4:5)=2+2 % This makes the last two columns of elements equal to 4
Dr2new =
  5×5 single matrix
     3    -5     0     4     4
     3    -5     1     4     4
     5    -5     4     4     4
     2    -3    -4     4     4
    -4     4    -2     4     4>> Dr1(9, :)=[] % The last row elements are removed
>> Dr1(9,:) =[]
Dr1 =
    0.4479    0.4916    0.4142    0.1393    0.6237
    0.9086    0.0534    0.0500    0.8074    0.7509
    0.2936    0.5741    0.5359    0.3977    0.3489
    0.2878    0.1467    0.6638    0.1654    0.2699
    0.1300    0.5893    0.5149    0.9275    0.8959
    0.0194    0.6998    0.9446    0.3478    0.4281
    0.6788    0.1023    0.5866    0.7508    0.9648
    0.2116    0.4141    0.9034    0.7260    0.6634>> Dr1(:, 4)=[ ] % The fourth column elements are removed
Dr1 =
    0.4479    0.4916    0.4142    0.6237
    0.9086    0.0534    0.0500    0.7509
    0.2936    0.5741    0.5359    0.3489
    0.2878    0.1467    0.6638    0.2699
    0.1300    0.5893    0.5149    0.8959
    0.0194    0.6998    0.9446    0.4281
    0.6788    0.1023    0.5866    0.9648
    0.2116    0.4141    0.9034    0.6634
In addition, you can create a new array from the elements of existing arrays:
>> NewDr = [Dr1(1:3,:), Dr2new(1:3, 2:4)] % Some elements of Dr1 and Dr2new are taken
NewDr =
  3×7 single matrix
  Columns 1 through 6
    0.4170    0.5388    0.1404    0.6865   -1.0000    2.0000
    0.7203    0.4192    0.1981    0.8346   -4.0000    4.0000
    0.0001    0.6852    0.8007    0.0183    5.0000    1.0000
  Column 7
    4.0000
    4.0000
    4.0000>> NewDr2 = [Dr3new(:,:); Dr2new(2:end, :)] % All elements of Dr3new and some from Dr2new
NewDr2 =
  9×5 int8 matrix
    1   -1    2   -3    1
    0    0    0    0    1
   -4    5    1   -1    1
   -4   -2    3    5    1
   -5   -5   -5   -5   -5
    4   -4    4    4    4
   -4    5    1    4    4
   -4   -2    3    4    4
    3    3   -2    4    4

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)

While working and processing different data sets and analyzing experimental data, it is quite common to work with NaN (not-a-number) values. NaN is the result of 0/0 or of importing character strings as numerical data sets. NaN is also the result of inf-inf (∞ - ∞) or when trying to interpolate beyond a given range. So, how do you handle NaN values in numerical arrays? There are a few ready-to-use functions/tools in MATLAB that handle NaNs. Let’s take a look at the following examples:
% Given:
A_var = [-8 10 NaN 9 4 -4 -7; 9 NaN 9 4 -10 9 0; -8 10 NaN 5 -10 -1 NaN]
A_var =
 -8 10 NaN 9 4 -4 -7
  9 NaN 9 4 -10 9 0
 -8 10 NaN 5 -10 -1 NaN
How do you compute the summation of the given numerical array, A_var? Note that sum() computes the sum of the columns of a matrix, if the matrix has more than one row and column. If the matrix is a row matrix, it computes the sum of all the row elements.
>> sum(A_var)
ans =
 -7 NaN NaN 18 -16 4 NaN

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?

One solution is to remove all NaN components of the array A_var by replacing them with 0. Otherwise, the summation will not give numerical results. You can substitute all NaN components using element-wise substitution, one by one. Or you can do it with a single command by recalling the indexes of all the NaN components.
>> A_var(5)=0 % Element by element change
A_var =
 -8 10 NaN 9 4 -4 -7
  9 0 9 4 -10 9 0
 -8 10 NaN 5 -10 -1 NaN
>> A_var([7 9 21])=[0, 0, 0] % All at once or % A_var([7 9 21])=0
A_var =
 -8 10 0 9 4 -4 -7
  9 0 9 4 -10 9 0
 -8 10 0 5 -10 -1 0
Now the summation can be performed:
>> sum(A_var)
ans =
 -7 20 9 18 -16 4 -7

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.

Here is a second solution. The nansum() MATLAB built-in function handles the summation of numerical arrays with NaN components (elements).
>> A_var = [-8 10 NaN 9 4 -4 -7; 9 NaN 9 4 -10 9 0; -8 10 NaN 5 -10 -1 NaN]
A_var =
 -8 10 NaN 9 4 -4 -7
  9 NaN 9 4 -10 9 0
 -8 10 NaN 5 -10 -1 NaN
>> nansum(A_var)
ans =
 -7 20 9 18 -16 4 -7

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.

There’s also a third way, by using logical indexing. It’s widely employed when working with large data sets, in order to sum the data, compute the mean or average values, plot the values, and perform other arithmetical matrix/array operations.
>> Index1=isnan(A_var) % Finds which elements of A_var are NaN and sets them equal to 1
Index1 =
 3×7 logical array
 0 0 1 0 0 0 0
 0 1 0 0 0 0 0
 0 0 1 0 0 0 1
>> A_var(Index1)=0 % Assigning all NaN elements to "0"
A_var =
 -8 10 0 9 4 -4 -7
  9 0 9 4 -10 9 0
 -8 10 0 5 -10 -1 0
>> sum(A_var)
ans =
 -7 20 9 18 -16 4 -7

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.

There is also an alternative logical indexing function introduced in recent versions of MATLAB called ismissing() . It’s used to identify missing data elements in numerical arrays.
Index2=ismissing(A_var) %Identifies all missing elements hidden behind NaN
Index2 =
 3×7 logical array
 0 0 1 0 0 0 0
 0 1 0 0 0 0 0
 0 0 1 0 0 0 1
>> A_var(Index2)
ans =
 NaN
 NaN
 NaN
 NaN
>> A_var(Index2)=0
A_var =
 -8 10 0 9 4 -4 -7
  9 0 9 4 -10 9 0
 -8 10 0 5 -10 -1 0
The logical indexing approach is very efficient and flexible and it can be applied to many other cases as well. For instance, you can easily identify all negative elements of a given data set or all elements within certain value ranges . Let’s take the following numerical array (of 7 by 7) generated by randi() and separate out all the elements greater than 3 but smaller than 9, then equate all of them to 5.
>> B_var = randi([0, 25], 7) % This creates uniform distributed integers within [0, 25] of 7-by-7 size
B_var =
 25 1 17 21 1 11 12
 18 13 13 2 10 0 8
 13 2 25 3 13 25 24
 12 21 16 4 10 4 23
 1 21 20 10 17 2 1
 17 18 11 21 16 9 19
 1 3 11 20 7 5 6
>> IndexB = find(B_var>3 & B_var<9)
IndexB =
 25
 35
 39
 42
 44
 49
>> B_var(IndexB)=5
B_var =
 25 1 17 21 1 11 12
 18 13 13 2 10 0 5
 13 2 25 3 13 25 24
 12 21 16 5 10 5 23
 1 21 20 10 17 2 1
 17 18 11 21 16 9 19
 1 3 11 20 5 5 5

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

MATLAB can recognize characters based on ASCII/ANSI character symbols in the form of numerical arrays. For example:
>> Ach1 = 'matlab' % Character type of variable
Ach1 =
 ' matlab '
>> Bch2 = ' mathworks ' % Character type of variable
Bch2 =
 ' mathworks '
>> Cch3= ' matlab belongs to mathworks ' % Character type of variable
Cch3 =
 'matlab belongs to mathworks'
>> Dch4 = 'www.mathworks.com' % Character type of variable
Dch4 =
 ' www.mathworks.com '
These are character type variables, but when the arithmetical operations are performed on these variables, they become numerical arrays .
>> format short
>> Aa1 =Ach1+0
Aa1 =
 109    97   116   108    97    98
>>Ba2 = Bch2+0
Ba2 =
 109    97   116   104   119   111   114   107   115    32
>> Ca3=Cch3+0
Ca3 =
 Columns 1 through 12
   109    97   116   108    97    98    32    98   101   108   111   110
  Columns 13 through 24
   103   115    32   116   111    32   109    97   116   104   119   111
  Columns 25 through 28
   114   107   115    32>> Da4 =Dch4+0
Da4 =
 Columns 1 through 12
   119   119   119    46   109    97   116   104   119   111   114   107
  Columns 13 through 17
   115    46    99   111   109
So, behind these numbers are the characters according to ASCII/ANSI standards. It is possible to get the character representations of the new variables using the MATLAB function char() .
>> char(Aa1)
ans =
 'matlab'
>> char(Ba2)
ans =
 'mathworks'
>> char(Ca3)
ans =
 'matlab belongs to mathworks'
>> char(Da4)
ans =
 'www.mathworks.com'
The following variables reside in the workspace:
 A 1x1 8 double
 A1New 2x6 12 uint8
 ABC 1x3 24 double
 Aa1 1x6 48 double
 Ach1 1x6 12 char
 Aone 2x6 96 double
 B 1x1 8 double
 Ba2 1x9 72 double
 Bch2 1x9 18 char
 Bzero 5x6 240 double
 Ca3 1x27 216 double
 Cch3 1x27 54 char
 Ceye 6x6 288 double
 DE 2x4 64 double
 Da4 1x17 136 double
 Dch4 1x17 34 char
 Dr1 8x4 256 double
 Dr2 4x6 192 double
 Dr2new 5x5 100 single
 Dr3 5x5 200 double
 Dr3new 5x5 25 int8
 Drow 1x4 32 double
 Erow 1x7 56 double
 Fcol 4x1 32 double
 NewDr 3x7 84 single
 NewDr1 3x7 84 single
 NewDr2 9x5 45 int8
 ans 1x17 34 char

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

The function handle is a special MATLAB data type that’s used to store a link to an expression or a function. By calling a function handle, we invoke the expression or function stored within that specific function handle. The function handle is one of the most useful features in MATLAB. For instance, function handles are used in various simulations and calculations of functions and mathematical expressions, in solving various equations and problems, and in user interface developments. They are also widely employed in solving differential equations. The syntax is rather intuitive and can be in two forms:
  • Function_handle_name =@MYfunction

  • Function_handle_name=@(variable1, variable2, ...)([expression1, expression2, ...])

Let’s look at several examples of how to generate function handles:
F1 = @MY_function;

Where MY_function is a function file, function expression, or another function handle.

For example:
function x = MY_function(a, b, c)
% MY_function.m is a function file that solves the quadratic equation w.r.t. % a  user entries for a, b, c and outputs the found solutions.
D= b^2-4*a*c;
x1 = (-b+sqrt(D))/(2*a);
x2 = (-b-sqrt(D))/(2*a);
x = [x1; x2];
end
We can test the function handle called F1 with the following command:
>> x = F1( 1, 2, 3)
x =
  -1.0000 + 1.4142i
  -1.0000 - 1.4142i

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.

Note that more detailed explanations of features of the function files (e.g., MY_function.m) and how to create them is found in Chapter 2, “Programming Essentials”.
  • f(x, a1, a2, a3 ) = a1x2 + a2x + a3;

>> f =@(x,a1,a2,a3)(a1*x^2+a2*x+a3)
f =
 function_handle with value:
 @(x,a1,a2,a3)(a1*x^2+a2*x+a3)
Moreover, the function handles can be used to define a function of functions. For example, H = 2esin(x) can be expressed in three ways with the following function of functions:
>> ff1 = @(x) sin(x); ff2 = @(ff1)exp(ff1); ff3 = @(ff2)2*ff2;    % 1 – Way
>> gg1 = @(x)sin(x); gg2 = @(x)exp(gg1(x)); ff3 = @(x) 2*gg2(x);   % 2 – Way
>> hh3=@(x)2*exp(sin(x));                                         % 3 – Way
It’s quite straightforward to perform computations from function handles:
>> ff3(ff2(ff1(pi)))
ans =
    2.0000
>>  gg3(pi)
ans =
   2.0000e+00
>> hh3(pi)
ans =
   2.0000e+00
>> x=1.3; a1=2; a2=-3; a3=13; f (x, a1, a2, a3)
ans =
 12.48
>> x=1.3; a1=[2, 3]; a2=[-3, 4]; a3=[11,13]; f2(x, a1, a2, a3)
ans =
   10.4800   23.2700
>> x=1:3; a1=2; a2=-3; a3=11; f2(x, a1, a2, a3)
Error using  ^  (line 51)
Incorrect dimensions for raising a matrix to a power.
Check that the matrix is square and the power is a
scalar. To perform elementwise matrix powers, use
'.^'.
Error in @(x,a1,a2,a3)(a1*x^2+a2*x+a3)
In the last part, the expression of f (x,a1,a2,a3) needs to be fixed for element-wise matrix operations.
>> f =@(x,a1,a2,a3)(a1*x.^2+a2*x+a3)
f =
  function_handle with value:
    @(x,a1,a2,a3)(a1*x.^2+a2*x+a3)>> x=1:3; a1=2; a2=-3; a3=11; f(x, a1, a2, a3)
ans =
    10    13    20
An alternative version of the function handle is the inline function . It’s similar to the function handle. Note that the inline function will be removed in future releases of MATLAB.
>> F1=inline('a1*x^2+a2*x+a3', 'a1', 'a2', 'a3', 'x')
F =
 Inline function:
 F (a1,a2,a3,x) = a1*x^2+a2*x+a3
Now, the inline functions can be evaluated with specific values of variables—x, a1, a2, and a3.
>> x=1.3; a1=2; a2=-3; a3=13; F(a1, a2, a3, x)
ans =
   12.4800
It is important while employing the function handles to follow the order of the variables. In other words, while calling them, you need to follow the sequence of the input variable values. For example:
>> x=1.3; a1=2; a2=-3; a3=13;
>> f =@(x,a1,a2,a3)(a1*x.^2+a2*x+a3);
>> f(x, a1, a2, a3)
ans =
   12.4800
>> f( a1, a2, a3, x)
ans =
   15.3000
The function handles can take different predefined input variables:
>> f =@(x,a1,a2,a3)(a1*x.^2+a2*x+a3);
>> y=1.3; b1=2; c2=-3; d3=13;
>> f(y,b1,c2,d3)
ans =
   12.4800
Figure 1-12 shows the list of variables and function handles created in this section that reside in the workspace.
../images/471979_1_En_1_Chapter/471979_1_En_1_Fig12_HTML.jpg
Figure 1-12

Variables residing in the workspace

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

Logical arrays are very important for programming and Boolean operations . The local answers are 0s and 1s. 0 means that a statement or condition is not true and 1 means that a statement is true. There are a few ways that logic arrays can be generated in MATLAB. You can apply the comparative analysis within numerical arrays or verify them or define their types. The following Boolean logical arrays are based on existing variables created in the previous sections.
>>A = 2; B = -3.25; C=(A+B)^2; ABC=[A, B, C];
>> isnumeric(A)
ans =
 logical
 1
>> Ach1 = 'matlab';
>> isstr(Ach1)
ans =
 logical
 1
>> ABC_logic=ABC>=2
ABC_logic =
 1×3 logical array
 1 0 0
>> Seed = 1; rng(Seed);   % Setting up the random number generator to generate permanent numbers.
>> Dr1 = rand(4, 5)
>> Dr1 = rand(4, 5)
Dr1 =
    0.0500    0.9446    0.1393    0.9275    0.8833
    0.5359    0.5866    0.8074    0.3478    0.6237
    0.6638    0.9034    0.3977    0.7508    0.7509
    0.5149    0.1375    0.1654    0.7260    0.3489
>> Dr1Logic=Dr1>0.5 & Dr1<=0.71
>> Dr1Logic=Dr1>0.5 & Dr1<=0.71
Dr1Logic =
  4×5 logical array
   0   0   0   0   0
   1   1   0   0   1
   1   0   0   0   0
   1   0   0   0   0

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().

You can use the evaluated logical arrays to index arrays and find out which values meet set conditions and which ones do not. For example, in the previous examples, ABC_logic states that the first element of ABC meets the set condition and is greater than or equal to 2. Similarly, the Dr1Logic array states that three elements in row 2 and one element in row 5 are greater than 0.5 and less than or equal to 0.71. Now you can determine which elements meet the set conditions by using indexing operations .
>> Index=find(Dr1>0.5 & Dr1<=0.71)
>> Index=find(Dr1>0.5 & Dr1<=0.71)   % Index numbers indicate which element has met the condition.
Index =
     2
     3
     4
     6
    18>> Dr1(Index)                % The element meeting the set conditions
ans =
    0.5359
    0.6638
    0.5149
    0.5866
    0.6237
An alternative way of finding these true values is the following:
>> Dr1Logic.*Dr1
ans =
         0         0         0         0         0
    0.5359    0.5866         0         0    0.6237
    0.6638         0         0         0         0
    0.5149         0         0         0         0
As another example, let’s find the “0” elements in an array generated by the random integer number generator, in order to generate integer numbers within [-2 2], filling the 5-by-5 square matrix:
>> Seed = 1; rng(Seed);   % Setting up the random number generator to generate permanent numbers.
>> Hr=randi([-2, 2], 5)
Hr =
     0    -2     0     1     2
     1    -2     1     0     2
    -2    -1    -1     0    -1
    -1    -1     2    -2     1
    -2     0    -2    -2     2>> Ind=(~Hr)    % Locates which elements of Hr are equal to "0"
Ind =
  5×5 logical array
   1   0   1   0   0
   0   0   0   1   0
   0   0   0   1   0
   0   0   0   0   0
   0   1   0   0   0
In this section, we generated the numerical and logic matrices and character strings, as shown in Figure 1-13.
../images/471979_1_En_1_Chapter/471979_1_En_1_Fig13_HTML.jpg
Figure 1-13

Variables residing in the workspace

More uses/examples of logical arrays and indexing are discussed in other sections of the book.

Table Arrays

The table arrays are a newly introduced tool in MATLAB and thus, in older versions of MATLAB, table arrays cannot be generated. Table arrays are particularly useful for preparing reports and displaying/presenting the simulation/analysis results obtained in arrays of several columns and rows, each of which represents certain variables. They are used to collect heterogeneous data and metadata into a single container in a tabular data format. Table Arrays can accommodate variables of different types, sizes, units, etc. They are often used to store experimental data, with rows representing different observations and columns representing different measured variables. They display the arrays in a more informative and tabulated format by indicating names of the columns and rows by respective assigned names. Let’s look at several examples of creating Table Arrays with the table() command by using the existing variables created in the previous sections.
>> A1new = [1 2 3; 3 4 5; 7 8 9];
>> A1Tab=table(A1new)
A1Tab =
  3×1 table
       A1new
    ___________
    1    2    3
    3    4    5
    7    8    9>> B1new = A1new/5;
>> B1Tab=table(B1new)
B1Tab =
  3×1 table
          B1new
    _________________
    0.2    0.4    0.6
    0.6    0.8      1
    1.4    1.6    1.8
In these cases, the Table Arrays A1Tab and B1tab are created as column tables from A1New and B1New, respectively. It is also possible to obtain/create tables from the existing arrays (arrays, cells, and structures) by using array2table(), cell2table(), and struct2table() commands:
>> A1Tab2=array2table(A1New) % Column names are not specified
>> A1Tab2=array2table(A1new)
A1Tab2 =
  3×3 table
    A1new1    A1new2    A1new3
    ______    ______    ______
      1         2         3
      3         4         5
      7         8         9   >> >> Ach1Tab=array2table(A1new, 'variablenames',{'a','b','c'})
Ach1Tab =
  3×3 table
    a    b    c
    _    _    _
    1    2    3
    3    4    5
    7    8    9 >> C1new = [A1new, B1new]
C1new =
    1.0000    2.0000    3.0000    0.2000    0.4000    0.6000
    3.0000    4.0000    5.0000    0.6000    0.8000    1.0000
    7.0000    8.0000    9.0000    1.4000    1.6000    1.8000
>> Dr1Tab=array2table(C1new, 'variablenames', {'v1', 'v2', 'v3', 'v4', 'v5', 'v6'})
Dr1Tab =
  3×6 table
    v1    v2    v3    v4     v5     v6
    __    __    __    ___    ___    ___
    1     2     3     0.2    0.4    0.6
    3     4     5     0.6    0.8      1
    7     8     9     1.4    1.6    1.8

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 ../images/471979_1_En_1_Chapter/471979_1_En_1_Fign_HTML.jpg 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.

Let’s look at several examples that create cell arrays with different types of arrays and generate new ones.
>> Acell = cell(5,5) % Creates an empty cell of size 5-by-5
>> Acell = cell(3,4)
Acell =
  3×4 cell array
    {0×0 double}    {0×0 double}    {0×0 double}    {0×0 double}
    {0×0 double}    {0×0 double}    {0×0 double}    {0×0 double}
    {0×0 double}    {0×0 double}    {0×0 double}    {0×0 double}% Each cell of the cell array Acell will be filled with the Arrays
>> A0 = 13; A1new = [1 2 3; 3 4 5; 7 8 9];
>> Acell{1,1}=A0  % Cell (1, 1) is filled with A0
Acell =
  3×4 cell array
    {[      13]}    {0×0 double}    {0×0 double}    {0×0 double}
    {0×0 double}    {0×0 double}    {0×0 double}    {0×0 double}
    {0×0 double}    {0×0 double}    {0×0 double}    {0×0 double}
>> Acell{1,2}=A1new  % Cell (1, 2) is filled with A1new
Acell =
  3×4 cell array
    {[      13]}    {3×3 double}    {0×0 double}    {0×0 double}
    {0×0 double}    {0×0 double}    {0×0 double}    {0×0 double}
    {0×0 double}    {0×0 double}    {0×0 double}    {0×0 double} >> Ach1Tab=array2table(A1new, 'variablenames',{'a','b','c'});
>> Acell{1,3}=Ach1Tab  % Cell (1, 3) is filled with Ach1Tab
Acell =
  3×4 cell array
    {[      13]}    {3×3 double}    {3×3 table }    {0×0 double}
    {0×0 double}    {0×0 double}    {0×0 double}    {0×0 double}
    {0×0 double}    {0×0 double}    {0×0 double}    {0×0 double} >> C1 = 'matlab';
>> Acell{1,4}=C1  % Cell (1, 4) is filled with C1
Acell =
  3×4 cell array
    {[      13]}    {3×3 double}    {3×3 table }    {'matlab'  }
    {0×0 double}    {0×0 double}    {0×0 double}    {0×0 double}
    {0×0 double}    {0×0 double}    {0×0 double}    {0×0 double} >> D1 = A1new>3 & A1new<9
D1 =
  3×3 logical array
   0   0   0
   0   1   1
   1   1   0 >> Acell{2,2}=D1  % Cell (2, 2) is filled with D1 logical array
Acell =
  3×4 cell array
    {[      13]}    {3×3 double }    {3×3 table }    {'matlab'  }
    {0×0 double}    {3×3 logical}    {0×0 double}    {0×0 double}
    {0×0 double}    {0×0 double }    {0×0 double}    {0×0 double} >> f=@(x, a1, a2, a3)(a1*x^2+a2*x+a3);
>> Acell{2,3}=f  % Cell (2, 3) is filled with f function handle
Acell =
  3×4 cell array
    {[      13]}    {3×3 double }    {3×3 table      }    {'matlab'  }
    {0×0 double}    {3×3 logical}    {function_handle}    {0×0 double}
    {0×0 double}    {0×0 double }    {0×0 double     }    {0×0 double} >> Acell{3,1}= 'This is a cell array' % Entered character strings into Cell array: Cell (3, 1)
Acell =
 3×4 cell array
 {[                13]}    {3×3 double }    {3×3 table      }       {'matlab'  }
 {0×0 double          }    {3×3 logical}    {function_handle}       {0×0 double}
 {'This is a cell ...'}    {0×0 double }    {0×0 double     }       {0×0 double}>> Acell{3,2}=rand(5,6) % Entered numerical array into Cell array: Cell(3,2)
Acell =
  3×4 cell array
 {[               13]}    {3×3 double }    {3×3 table      }    {'matlab'  }
 {0×0 double         }    {3×3 logical}    {function_handle}    {0×0 double}
 {'This is a cell ...'}    {5×6 double }    {0×0 double     }    {0×0 double}
To access and view the contents of the cell arrays , use the following commands.
>> Acell{1,1}
ans =
    13>> Acell{1,4}
ans =
    'matlab'
>> Acell{2,3}
ans =
  function_handle with value:
    @(x,a1,a2,a3)(a1*x^2+a2*x+a3)>> Acell{7}
ans =
  3×3 table
    a    b    c
    _    _    _
    1    2    3
    3    4    5
    7    8    9
>> Acell{8}
ans =
  function_handle with value:
    @(x,a1,a2,a3)(a1*x^2+a2*x+a3)
By double-clicking on the cell variable name in the workspace, the contents of the cell can be viewed, as shown in Figure 1-14.
../images/471979_1_En_1_Chapter/471979_1_En_1_Fig14_HTML.jpg
Figure 1-14

Variables in the workspace and contents of the Acell cell array

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.

Structure arrays store data in different fields or field names, which you can access by their names. For example:
% Person 1: Name - SE; DOB - June 6, 1982; Profession - professor
WHO(1).Name = 'SE';
WHO(1).DOB = '06.06.1982';
WHO(1).Profession = 'professor';
% Person 2: Name - NE; DOB - Dec 12, 1992; Profession - designer
WHO(2).Name = 'NE';
WHO(2).DOB = '12.12.1982';
WHO(2).Profession = 'designer';
The structure variable WHO contains information about two people. The data contains their names, date of birth, and profession.
>>WHO =
  1×2 struct array with fields:
    Name
    DOB
    Profession
>> WHO(1)
ans =
  struct with fields:
          Name: 'SE'
           DOB: '06.06.1982'
    Profession: 'professor'
>> WHO(2)
ans =
  struct with fields:
          Name: 'NE'
           DOB: '12.12.1982'
    Profession: 'designer'
Note that we saved only one variable that is in a structure array form. If you want to have access to a specific field of the created structure, you call that field name along with the structure name:
>> WHO(1).Name   % To access to the name field of a person 1
ans =
    'SE'
>> WHO(1).Profession   % To access to the profession field of a person 1
ans =
    'professor'
>> WHO(2).DOB    % To access to the DOB field of a person 2
ans =
    '12.12.1982'
Besides this approach of creating structure arrays, there are several other ways to set up or create them. Let’s look at some examples. Another way is to create an empty structure with the struct() command . The empty structure will be filled with variables with the struct('FieldName', VALUE) command syntax . Note that the field names (variable names) cannot contain empty spaces or symbols, except for the underscore sign _.
>>  Astr1 = struct()
Astr1 =
  struct with no fields.
>> % Now we can assign/set up values and data fields inside the created empty structure: Astr1.
>> a = 2.1; A = [1, 2; 3, 4]; B = A<a; f = @(x)(a*x^2+x-a); C{1} =rand(3); C{2} = 'matlab';
>> D = 'mathworks.com';
>> F = table(magic(3));
>>  Astr1 = struct('Number', a, 'Matrix', A, 'Logic', B, 'F_Handle', f, 'Cell', C, 'Char', D, 'Table', F)
Astr1 =
  1×2 struct array with fields:
    Number
    Matrix
    Logic
    F_Handle
    Cell
    Char
    Table
Another way to create structure arrays is to assign their fields individually, as shown in the beginning with the example of creating the structure variable WHO.
>> Bstr.Number = a; Bstr.Matrix = A; Bstr.Logic = B; Bstr.F_Handle=f; Bstr.Cell=C; Bstr.Char = D;
>> Bstr.Table = F;
>> Bstr
Bstr =
  struct with fields:
      Number: 2.1000e+00
      Matrix: [2×2 double]
       Logic: [2×2 logical]
    F_Handle: @(x)(a*x^2+x-a)
        Cell: {[3×3 double]  'matlab'}
        Char: 'mathworks.com'
       Table: [3×1 table]
Now we can compare the two different ways we created the structure variables Astr and Bstr. Another way to create structure arrays is conversions; in other words, you convert existing cell type variables or table type variables into structure type variables with the cell2struct() and table2struct() commands.
>> % Cell variable C contains: Matrix C and String character 'matlab'
>> C{1} =rand(3); C{2} = 'matlab';
>> F_Names = {'Matrix', 'Char'};    % Field names/Headers
>> Cstr = cell2struct(C, Headers, 2) % 2 means two cells embedded
Cstr =
  struct with fields:
    Matrix: [3×3 double]
      Char: 'matlab'
Now let’s see how to convert a table array into a structure array with the table2struct() command.
>> F = table(magic(3));
>> Dstr = table2struct(F)
Dstr =
  3×1 struct array with fields:
    Var1
Figure 1-15 shows the list of variables saved in the workspace and the contents of the Astr and Bstr structure arrays .
../images/471979_1_En_1_Chapter/471979_1_En_1_Fig15_HTML.jpg
Figure 1-15

Created variables and Astr and Bstr structure arrays

This section has demonstrated via examples how to create seven different types of variables (arrays)—numerical arrays (scalar and array type variables), character strings, logical arrays, table arrays, cell and structure arrays, and function handles. You can remove from the workspace any of the created variables by using the clear or clearvars commands or using the right-mouse button options and Delete. From the Command Window, you can clear the variables from the workspace with the following commands.
>> clearvars a A  B% Removes variables a, A, B
>> clear ans C D % Removes variables ans, C, D

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.

For instance:
>> sin(pi)
ans =
 1.2246e-016
In MATLAB, sin(π) is not equal to 0. That is due to the fact that the number π is represented by the double precision number in MATLAB. We can demonstrate the precision issue by performing the calculations of the Pythagorean Theorem: 1 = sin2(t) + cos2(t).
t=0:pi/50:2*pi; F=1-(sin(t).^2+cos(t).^2); plot(t, F)

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).

It must be noted that MATLAB’s accuracy (precision) level depends on which data storage type is used to save data. For instance:
>> int8(128)*-5
ans =
 -128

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.>

In the M-file editor’s main tools menu (see Figure 1-16), there are five sub-sections—FILE, NAVIGATE, EDIT, BREAKPOINTS, and RUN. All of the tools in each subsection are quite intuitive. For example, the FILE sub-section has GUI tools used to create a new file or open existing files, save the current file, find M-files, compare different versions of the M-files with the same names, and print the current M-file. Similarly, the NAVIGATE subsection tools help a user move the cursor within the current file and find keywords and, if necessary, substitute them with other words. The EDIT subsection tools allow you to insert a new section into the current file, add or remove a comment line or wrap comments and add indents to make the file more readable. The BREAKPOINTS subsection enables you to debug/edit the current M-file code. Finally, the RUN subsection has GUI tools that run different cell sections of the current M-file step by step and run the current M-file and measure the evaluation time in different sections of the file. It should be noted that when writing M-files, the EDITOR window tools are mainly used.
../images/471979_1_En_1_Chapter/471979_1_En_1_Fig16_HTML.jpg
Figure 1-16

M-file editor’s main tools menu

The PUBLISH tools, shown in Figure 1-17, are used to generate report files in different file formats, such as HTML, DOC, PPT, etc. The PUBLISH window’s GUI tools are very intuitive and similar to many document editing software applications.
../images/471979_1_En_1_Chapter/471979_1_En_1_Fig17_HTML.jpg
Figure 1-17

M-file editor’s Publish tools menu

The VIEW tools, shown in Figure 1-18, are used to display several windows of M-files and MLX-files (documents) within one window area. You can split the view side by side or top to bottom by using the GUI tools called TILES, DOCUMENT TABS, or SPLIT DOCUMENT. The tickmark options in the DISPLAY subsection are very handy to display data-tips, show line numbers, and highlight the current line while editing M-files.
../images/471979_1_En_1_Chapter/471979_1_En_1_Fig18_HTML.jpg
Figure 1-18

M-file editor’s view tools menu

MLX-File Editor

The MLX-file (live editor) editor tab (shown in Figures 1-19, 1-20, and 1-21) contains many of the M-file editor tools along with several other different GUI tools. The LIVE EDITOR tab (see Figure 1-19) has one main different sub-section from the M-file editor, called TEXT, and it contains most of the functions of the PUBLISH tools of the M-file editor.
../images/471979_1_En_1_Chapter/471979_1_En_1_Fig19_HTML.jpg
Figure 1-19

MLX-file editor’s main tools menu

Moreover, the MLX-editor’s INSERT tab (see Figure 1-20) has a few very handy tools to write/edit equations directly in the MLX-file and insert subsections with comments. You can insert control GUI tools, such as slider and drop-down boxes, within the current MLX-file content.
../images/471979_1_En_1_Chapter/471979_1_En_1_Fig20_HTML.jpg
Figure 1-20

MLX-file editor’s INSERT menu

The VIEW window (shown in Figure 1-21) of the MLX-editor has some similar tools of the M-file editor’s VIEW and some other tools, such as DOCUMENT TABS, DISPLAY, OUTPUT, and LAYOUT, by which a user can display script (code) line numbers (excluding the comment lines), data-tips, full screen view, clean up the output, and show or hide output.
../images/471979_1_En_1_Chapter/471979_1_En_1_Fig21_HTML.jpg
Figure 1-21

MLX-file editor’s view tools menu

M-files and MLX-files can be created in several different ways—by using GUI buttons ../images/471979_1_En_1_Chapter/471979_1_En_1_Figo_HTML.jpg or ../images/471979_1_En_1_Chapter/471979_1_En_1_Figp_HTML.jpg 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: $$ alpha =-frac{pi }{2}dots frac{pi }{2},Delta alpha =frac{pi }{100};Fleft(alpha 
ight)=1-left({sin}^2alpha +{cos}^2alpha 
ight); $$

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.

The algorithm for solving this exercise is composed of the following six steps.
  1. 1.

    Insert some comments describing the given problem statement.

     
  2. 2.

    Define the input variable: $$ alpha =-frac{pi }{2}dots frac{pi }{2},Delta alpha =frac{pi }{100}; $$.

     
  3. 3.

    Perform the computation: F(α) = 1 − (sin2α + cos2α).

     
  4. 4.

    Define for which values of the input variable α the function values of F(α) = 0.

     
  5. 5.

    Plot the simulation results: α vs. F(α).

     
  6. 6.

    Publish all of the obtained results, including the whole script.

     
This is the script written directly in the M-file editor.
% Step 1. Problem statement
% MATLAB's precision is not absolute.
% Pythagorean Theorem: F = 1 - (sin^2 (alpha) + cos^2(alpha));
% Input variable: alpha = -0.5*pi ... 0.5*pi
% Step 2. Define the input variable
alpha = -pi/2:pi/100:pi/2;
% Step 3. Perform the computation
F = 1-(sin(alpha).^2+cos(alpha).^2);
% Step 4. Define for which values of alpha, F(alpha) = 0.
Findex=find(F==0);
F0=F(Findex);
% Step 5. Plot the simulation results: alpha vs. F(alpha)
plot(alpha, F, 'b-', alpha(Findex), F0, 'ro'),
legend('alpha vs F(alpha)', 'F(alpha) = 0')
title('Simulation of MATLAB"s precision via the Pythagorean Theorem '), grid on
xlabel('alpha'), ylabel('F(alpha) = 1-(sin(alpha)^2+cos(alpha)^2)')
% Step 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 ../images/471979_1_En_1_Chapter/471979_1_En_1_Figq_HTML.jpg 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 ../images/471979_1_En_1_Chapter/471979_1_En_1_Figr_HTML.jpg 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

See [6] also. Note that %% at the beginning initializes automatic recognition of the LaTEX compatible mathematical commands within Step 1.
%%
%% *% Step 1. Problem statement*
% MATLAB's precision is not absolute.
% Pythagorean Theorem: F = 1 - (sin^2 $$alpha$ + cos^2 $$alpha$ );
% Input variable: $$alpha$ = -0.5* $$pi$ ...0.5* $$pi$
%% *% Step 2. Define the input variable*
alpha = -pi/2:pi/100:pi/2;
%% *% Step 3. Perform the computation*
F = 1-(sin(alpha).^2+cos(alpha).^2);
%% *% Step 4. Define for which values of $$alpha$ $$F(alpha) =0$*
Findex=find(F==0); F0=F(Findex);
%% *% Step 5. Plot the simulation results: $$alpha$ vs. $$F(alpha)$*
plot(alpha, F, 'b-', alpha(Findex), F0, 'ro'),
legend('alpha vs F(alpha)', 'F(alpha) = 0')
title('The Pythagorean Theorem '), grid on
xlabel('alpha'), ylabel('F(alpha) = 1-(sin^2(alpha)+cos^2(alpha))')
%% *%Step 6. Publish all of the obtained results including the whole script*
After writing the script in the editor, save the M-file with a valid filename (e.g., P1.m). Now, to publish it as an HTML format, press the Publish ../images/471979_1_En_1_Chapter/471979_1_En_1_Figs_HTML.jpg button under the PUBLISH tab (see Figure 1-17). After pressing the button, the script is executed automatically and its HTML-formatted report will be generated, as shown in Figure 1-19.22
../images/471979_1_En_1_Chapter/471979_1_En_1_Fig22_HTML.jpg
Figure 1-22

The MATLAB-generated HTML-formatted report of the M-file called P1.m

3
../images/471979_1_En_1_Chapter/471979_1_En_1_Fig23_HTML.jpg
Figure 1-23

The MATLAB-generated HTML-formatted report of the M-file called P1.m

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.

Now let’s try the same procedure with the MLX-file editor. Note that the comments are edited using the TEXT tab tools of the MLX-editor (shown in Figure 1-19). The parts of the script are entered as text (comments) by using ../images/471979_1_En_1_Chapter/471979_1_En_1_Figt_HTML.jpg . The Step 1 … Step 2 … Step 3… Step 6 lines are made bold with ../images/471979_1_En_1_Chapter/471979_1_En_1_Figu_HTML.jpg.
Step 1. Problem statement
MATLAB's precision is not absolute.
Pythagorean Theorem: F = 1 - (sin^2 (alpha) + cos^2(alpha));
Input variable: alpha = -0.5*pi ... 0.5*pi
Step 2. Define the input variable
Step 3. Perform the computation
Step 4. Define for which values of alpha, F(alpha) = 0.
Step 5. Plot the simulation results: alpha vs. F(alpha)
Step 6. Publish all of the obtained results including the whole script
Note that there is an alternative way to make the chosen lines bold. That is to use %% followed by a blank space, as in the M-file editor. In this case, such editing is automatically detected as a header of the following section of the script. If you enter this in the Code section of MLX-editor:
%% Step 2. Define the input variable.

and press Enter, MATLAB automatically creates this bolded text header:

Step 2. Define the input variable.

Now, in between Step 2, Step 3, Step 5, and Step 6, the following executable commands are inserted by placing the cursor on the desired line and pressing the ../images/471979_1_En_1_Chapter/471979_1_En_1_Figv_HTML.jpg button from CODE sub-tab (see Figure 1-19). Finally, the complete code is obtained.
Step 1. Problem statement
MATLAB's precision is not absolute.
Pythagorean Theorem: F = 1 - (sin^2 (alpha) + cos^2(alpha));
Input variable: alpha = -0.5*pi ... 0.5*pi
Step 2. Define the input variable
alpha = -pi/2:pi/100:pi/2;
Step 3. Perform the computation
F = 1-(sin(alpha).^2+cos(alpha).^2);
Step 4. Define for which values of alpha, F(alpha) = 0.
Findex=find(F==0);F0=F(Findex);
Step 5. Plot the simulation results: alpha vs. F(alpha)
plot(alpha, F, 'b-', alpha(Findex), F0, 'ro'),
legend('alpha vs F(alpha)', 'F(alpha) = 0')
title('The Pythagorean Theorem'), grid on
xlabel('alpha'), ylabel('F(alpha) = 1-(sin(alpha)^2+cos(alpha)^2)')
Step 6. Publish all of the obtained results including the whole script

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 ../images/471979_1_En_1_Chapter/471979_1_En_1_Figw_HTML.jpg. When you press the ../images/471979_1_En_1_Chapter/471979_1_En_1_Figx_HTML.jpg button, the whole range of symbols, structures, and matrices will be opened as shown in the following image.

../images/471979_1_En_1_Chapter/471979_1_En_1_Figy_HTML.jpg
Now you bring the cursor where you want to insert the mathematical expressions and insert the symbols by selecting the necessary symbols, or by using LaTEX expressions. For example, alpha gives α. Enter the expressions of the Pythagorean formulation and input the variable range, then finalize the script.
Step 1. Problem statement
MATLAB's precision is not absolute
The Pythagorean Theorem: F = 1 − (sin2α + cos2α)
Input variable: α =  − 0.5α...0.5α
Step 2. Define the input variable
alpha = -pi/2:pi/100:pi/2;
Step 3. Perform the computation
F = 1-(sin(alpha).^2+cos(alpha).^2);
Step 4. Define for which values of α, F(α) = 0
Findex=find(F==0);
F0=F(Findex);
Step 5. Plot the simulation results: α vs. F(α)
plot(alpha, F, 'b-', alpha(Findex), F0, 'ro'),
legend('alpha vs F(alpha)', 'F(alpha) = 0')
title('The Pythagorean Theorem '), grid on
xlabel('alpha'), ylabel('F(alpha) = 1-(sin^2(alpha) +cos^2(alpha))')
Step 6. Publish all of the obtained results including the whole script
After executing the saved MLX-file (by pressing the Run button shown in Figure 1-19), you’ll get the script outputs via Output Inline in LAYOUT. See Figure 1-24 and Figure 1-25.
../images/471979_1_En_1_Chapter/471979_1_En_1_Fig24_HTML.jpg
Figure 1-24

MLX editor output of P2.mlx

../images/471979_1_En_1_Chapter/471979_1_En_1_Fig25_HTML.jpg
Figure 1-25

MLX editor output of P2.mlx

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

Exercises for Self-Testing

Exercise 1

Perform the following:
  1. 1.

    Find the Vibrating Logo demo from the pre-installed MATLAB demos and run it. Hint: membrane.

     
  2. 2.

    Locate Product Overview from the package’s Help Library.

     
  3. 3.

    Change the font type and size of the Command Window.

     

Exercise 2

Do the following:
  1. 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. 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

Given x = 2.25, y = 3.1 and z = 13.20, use MATLAB to evaluate the following expressions:
$$ A=sqrt[y]{ xy z-frac{z}{xy}}+{x}^2{y}^{frac{3}{2 }}{z}^{frac{5}{4}};B={e}^{- xyz}ln left(frac{xy}{z}
ight). $$

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

Create a script and save it as my_first_program.m.
  1. a)

    Your program should contain an input variable that is the length of a square side as a variable parameter in meters.

     
  2. b)

    Your program should calculate the area of a square and the volume of a cube.

     
  3. 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.

     
  4. d)

    Execute your script (my_first_program.m) from the Command Window.

     
  5. e)

    Execute your script (my_first_program.m) from the M-file Editor Window.

     

Exercise 10

Do/answer the following:
  • Which command displays what is stored in your MATLAB workspace?

  • Create $$ P=frac{pi }{4} $$ 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

Given:
C1 = Hello. I'm from NYC. What is your name?
D 1= I'm Dan.
C2 = Nice to meet you
D 2= Nice to meet u 2
Using these entries (C1, C2, D1, and D2), create a conversation displayed in the Command Window in the form of this dialogue:
'Hello.' 'I'm from NYC.'
'What is your name?' 'I'm Dan.'
'Nice to meet you.' 'Nice to meet u 2.'

Exercise 13

Do the following:
  1. 1.

    Change display data formats for the Command Window and make it a long e.

     
  2. 2.

    Where are the preferences settings of MATLAB saved?

     
  3. 3.

    What is the main function of the M-file finishdlg.m and what commands does it contain?

     

Exercise 14

Do the following:
  1. 1.

    Write a command in the Command Window that creates and opens an M-file called Ex14.m.

     
  2. 2.

    Edit your M-file Ex14.m so that it contains a command that changes the display format type.

     
  3. 3.

    Edit your M-file Ex14.m so that it contains a command that changes the current directory.

     
  4. 4.

    Edit your M-file Ex14.m so that it contains a command that displays the current date and time.

     

Exercise 15

Given:
>> day_ONE="MatlabDAY"; day_DUE=day_ONE+1.0
day_DUE =
 78 98 117 109 98 99 69 66 90

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

Create a structure composed of cell and numeric array elements called Matlab and classes:
  1. 1.

    Create a cell called Matlab that is composed of two sub-cells: {'Day#1', 'Start'}

     
  2. 2.

    Create a numeric array called classes that contains elements [$$ pi; 2pi; sqrt{pi }+2i $$]. 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 * etiθ. 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 [$$ 0,dots frac{pi }{2},pi dots frac{3pi }{2},2pi dots frac{5pi }{2},3pi dots 5pi $$] 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 $$ sqrt[5]{1.5ast {10}^{24}-{10}^{24}i} $$ in a most accurate way. Note that it is in a fifth root.

Exercise 21

Why does the following output look “strange”?
>> A=[4/5, 'matlab'+0, sin(pi)]
A =
 Columns 1 through 3
 3fe999999999999a 405b400000000000 4058400000000000
 Columns 4 through 6
 405d000000000000 405b000000000000 4058400000000000
 Columns 7 through 8
 4058800000000000 3ca1a62633145c07

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?

../images/471979_1_En_1_Chapter/471979_1_En_1_Figz_HTML.jpg

Exercise 23

Create the following array in the most efficient way (at least two different ways). Note the display format of the A2 elements.

../images/471979_1_En_1_Chapter/471979_1_En_1_Figaa_HTML.jpg

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.

../images/471979_1_En_1_Chapter/471979_1_En_1_Figab_HTML.jpg

Exercise 26

Given A5 = [1 2 3; 4 5 6; 7, 8, 9].
  1. 1.

    Obtain B5 from A5 using two arithmetic operations: B5 = [16, 9 4; 1 0 1; 4 9 16].

     
  2. 2.

    Obtain C5 from A5 and B5 by using relational logic (<, >) and arithmetic operations (+ 13).

     
C5 = [13 13 13; 14 14 14; 14 13 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: $$ I=left[egin{array}{ccc}1&amp; 0&amp; 0\ {}0&amp; 1&amp; 0\ {}0&amp; 0&amp; 1end{array}
ight] $$

Magic numbers: $$ M=left[egin{array}{ccc}8&amp; 1&amp; 6\ {}3&amp; 5&amp; 7\ {}4&amp; 9&amp; 2end{array}
ight] $$

Multiply the matrix by 2 and subtract it from the M matrix. Call the new matrix MI: $$ MI=left[egin{array}{ccc}6&amp; 1&amp; 6\ {}3&amp; 3&amp; 7\ {}4&amp; 9&amp; 0end{array}
ight] $$

Locate array L by locating/comparing the elements of MI that are greater than 1 and less than 6: $$ L=left[egin{array}{ccc}0&amp; 0&amp; 0\ {}1&amp; 1&amp; 0\ {}1&amp; 0&amp; 0end{array}
ight] $$
Table array TM from M:
Cell Array CA containing F, I, M, MI, L, TM
Structure SA containing F, I, M, MI, L, TM, CA.

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).

../images/471979_1_En_1_Chapter/471979_1_En_1_Figac_HTML.jpg
../images/471979_1_En_1_Chapter/471979_1_En_1_Figad_HTML.jpg
../images/471979_1_En_1_Chapter/471979_1_En_1_Figae_HTML.jpg

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.

../images/471979_1_En_1_Chapter/471979_1_En_1_Figaf_HTML.jpg

Exercise 33

Answer the following questions:
  1. 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. 2.

    Where does MATLAB display a list of stored variables and associated attributes?

     
  3. 3.

    The MATLAB user interface is customizable. (True/False)

     
  4. 4.

    MATLAB supports cell arrays only if they are numerical data, not strings. (True/False)

     
  5. 5.

    It is possible to put a table array variable into a cell array. (True/False)

     
  6. 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. 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

Answer the following array size and representation related questions:
  1. 1.

    Given a cell array ABBA with 10 cells, which command will recall the elements residing in cell 3 of ABBA?

     
  2. 2.

    Given a 5-by-5 array (matrix) called A, A(4:end, 3:4), it will produce a matrix of what size?

     
  3. 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

Given in the Command Window:
>> x=linspace(-13, 0), F(x)=2*x^2+2*x-1;

There are errors. Find errors and fix them. What is the size of x and F now?

Exercise 37

Write the answers to the following questions:
  1. 1.

    How do you change a working directory to: C:UsersPublic and add this path for searching?

     
  2. 2.

    Create a new directory called MYdir inside the C:UsersPublic directory.

     
  3. 3.

    How do you find out which variables are stored in your MATLAB workspace?

     

Exercise 38

Answer the following array related questions on equally spaced data points:
  1. 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, …, e8and [ tan(e0), tan(e1), tan(e2), …, tan(e8)], respectively in the most efficient way.

     
  2. 2.

    Generate these vector spaces in two different ways: [-100, -90, -80, ... 100], [-100, -99, -98, ... 100].

     
  3. 3.

    How do you generate 500 data points equally spaced within −π. . π ]?

     

Exercise 39

Answer the following logical indexing and logical array related questions:
  1. 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. 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. 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. 4.

    Given >> GAB=find(AG>0 & AG<13), AG(GAB)

    What numbers are behind GAB and how are they related to AG?

     
  5. 5.

    Given >> 13>10; -1.2<=7.8; -11+13>=3

    Why are we getting 0s and 1s?

     
  6. 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. 7.

    Given >>B = randi([0, 13], 5); k=find(B>=3 & B<=5)

    Which numbers are in k with reference to B?

     

Exercise 40

Create an * .m file called ARRAY_1.m and write the following:
  1. 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. 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. 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. 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. 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. 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. 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. 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

Create an *.mlx file called Ex41.mlx and write in it the following:
  1. 1.

    The command that creates a cell array called Q1 with six empty column cells.

     
  2. 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. 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. 4.

    The command that generates the following array using pascal() (a MATLAB built-in matrix function):

     
../images/471979_1_En_1_Chapter/471979_1_En_1_Figag_HTML.jpg

And by applying logical indexing (logical array) and element-wise matrix multiplication operations, generate the following array:

../images/471979_1_En_1_Chapter/471979_1_En_1_Figah_HTML.jpg
  1. 5.

    The command that creates a structure array called S5 and the command that writes its Q1, H, and HLG.

     
  2. 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

Create an *.mlx file (called Ex42.mlx) and add all necessary comments, such as questions, equations, explanations, and other relevant remarks. Also write in these commands:
  1. 1.

    Generate two column arrays with 202 equally spaced data points in two ways: = −2π…2π; β = −3600…3600.

     
  2. 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. 3.

    Create an array (called Solution) of five columns containing: α, F(α), β, H(β), S

     
  4. 4.

    Create a table of arrays. The table of variables should be called TVall and has to be in the following format.

     
../images/471979_1_En_1_Chapter/471979_1_En_1_Figai_HTML.jpg
  1. 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.

     
  2. 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.

     
  3. 7.

    Create a structure of arrays called ABFSH_struct containing: SOLUTION, TVall, FSH_pos, and ABS_0 from Steps 3, 4, 5, and 6.

     
  4. 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

Create an *.m file (called Ex43.m) that performs the following operations:
  1. 1.

    Clears the workspace and Command Window from all entries.

     
  2. 2.

    Closes all open figure windows.

     
  3. 3.

    Creates a new directory called C:DocumentsEx43.

     
  4. 4.

    Changes the current directory of MATLAB to a newly created directory: C:DocumentsEx43.

     
  5. 5.

    Computes t = [0, 3π] with ∆t = π/200, $$ {f}_1(t)=3mathit{sin}left(frac{3t}{2}
ight) $$, $$ {f}_2(t)=2cos left(frac{2t}{5}
ight) $$

     
  6. 6.

    Saves the computation results (t f1(t), f2(t)) in a .mat file called Ex43.mat.

     

Exercise 44

Create an *.m file (called Ex44.m) that performs the following operations:
  1. 1.

    Changes the current directory of MATLAB to the MATLAB’s root directory (Hint: matlabroot).

     
  2. 2.

    Removes the directory created in Exercise 43: C:DocumentsEx43.

     
  3. 3.

    Displays the MATLAB’s root directory in the Command Window.

     
  4. 4.

    Creates two function handles: $$ mathrm{r}=frac{1}{2}mathrm{a}{t}^2+{oldsymbol{v}}_ot+{mathrm{r}}_0 $$ and $$ A=P{left(1+frac{r}{n}
ight)}^{nt} $$.

     
  5. 5.

    Saves the current path and the function handles in a structure array called EX44.

     
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.223.239.226