IN THIS CHAPTER
Understanding the MATLAB file structure
Working with MATLAB files
Storing data on disk
Computers have two kinds of storage bins: temporary memory in RAM and permanent memory on a storage device such as a hard drive. (There are also hard drive-like online storage bins, but they’ll count as hard drives for most of this chapter.) To make anything you create using MATLAB permanent, you must place it on the hard drive. Unfortunately, hard drives are huge, and if you want to find the data again later, you need to know where you placed the information. That’s why knowing something about the MATLAB file structure is important — because you use it to find a place to store your data and to recover that data later.
Data is stored in files, while folders are used to organize the data. To load your data into MATLAB, you must first find the right folder, open it, and then open the file. It works much the same as a filing cabinet. As long as the drawer is closed and the file folder remains inside, the data is inaccessible. Note as well that some of your data may be in the wrong format. When data formatting is a problem, you need to import the data into MATLAB so that MATLAB can make use of it. The same holds true of other applications. When you want to use your MATLAB data with another application, you export it to that application.
The final section of this chapter discusses how to save your work for later use. The act of saving your work moves the data from temporary storage in RAM to permanent storage on the hard drive in a file. Later, when you need to access the data again, you open the file, which moves it from the hard drive into RAM. There is nothing mystical about this process. You perform the same sorts of tasks in the real world every day. Just think about how you use files in a filing cabinet the next time you open one.
You don’t have to type the source code for this chapter manually. In fact, using the downloadable source is a lot easier. You can find the source for this chapter in the \MATLAB2\Chapter04 folder of the downloadable source. When using the downloadable source, you may not be able to work through some of the hands-on examples because the example files will already exist on your system. In this case, you can create an alternative folder, Chapter04a, to hold the results of the hands-on exercises. You can find details of where to find the downloadable source in the Introduction.
Examining MATLAB’s File Structure
To keep your data permanently, you must store it on disk. Of course, you could just store it anywhere, but then finding it later would be intensely difficult. In fact, given the size of today’s hard drives, you might well retire before you find the data again. (And, if you’re storing that data using an online hard drive, just think about how long it would take to search the Internet.) So, relying on some organized method of storing your information is important.
Applications also rely on specific file types when storing information. The main reason for using a specific file type is to allow the application to recognize its data among all the other data on your drive. Imagine the chaos if every application used the .txt file extension for every file, but each application created its own sort of .txt file that isn’t readable by any other application. Not only you but also the computer would become confused. In addition, using specific file types lets you know what sort of data the file contains.
MATLAB lets you identify the particular kind of information a file holds through the use of unique file extensions. For example, scripts and functions are stored in files with an .m extension; Live Scripts and Live Functions appear in .mxl files; variables are stored in files with a .mat extension; and plots are stored in files with a .fig extension. In addition, you can organize your data using a file structure. You can perform all these management tasks from within MATLAB using either the application’s GUI or commands. The following sections tell you how all these features work.
Understanding the MATLAB files and what they do
MATLAB provides specific file types for specific needs. The following list tells you about the MATLAB file types and describes their uses:
· .fig: Provides access to any plots or other graphics you create. Keep in mind that the file contains all the information required to reconstruct the graphic, but does not contain the graphic itself. This approach means that your image is accessible on any platform that MATLAB supports.
A lot of people have asked whether they can access .fig files without necessarily having to display the graphic image itself. It turns out that .fig files are actually .mat files in disguise. The file format is the same (even though the content between the two file types differs). In fact, you can simply rename a .fig file with a .mat extension and use Import Data on the Home tab to import it. You can also use the load('untitled.fig', '-mat') command, where 'untitled.fig' is the name of the file. Inside the file, you see two variables: hgM_070000 (contains the graphic objects, which are accessible only when the figure is visible) and hgS_070000 (contains the user data). Wandering through the two variables will tell you a lot about how MATLAB works with figures. For example, hgS_070000.children(2).children.properties.XData displays the x-axis data used to generate the plot. As another example, hgM_070000.GraphicsObjects.Format3Data.Color = [0.9900, 0, 0] turns the frame around the figure red.
· .m: Holds a MATLAB script. This is a platform-independent file, so you can use the same scripts on whatever platform you’re working on at the time. This file also allows you to create a script on one platform and share it with others, even when they use a different platform than you do. MATLAB script files are always written using the MATLAB language.
· .mat: Provides access to any data you saved on disk. Opening this file starts the Import Wizard to load the data into the MATLAB workspace.
· .mdl: Contains an older version of a Simulink model (see .slx below for details on the Simulink model). MATLAB recommends updating these files to the .slx format using the procedure at https://www.mathworks.com/help/simulink/examples/converting-from-mdl-to-slx-model-file-format-in-a-simulink-project.html.
· .mex*: Contains compiled executable code that extends MATLAB functionality in some manner. You execute these files just as you would a script program. The original code is written in either FORTRAN or C++ and then compiled for a specific platform. Each platform has a unique extension associated with it, as shown in the following list:
· .mexa64: Linux
· .mexmaci64: Mac OS X
· .mexw32: 32-bit Windows
MATLAB 32-bit extensions won’t run in a 64-bit copy of MATLAB (see https://www.mathworks.com/matlabcentral/answers/225383-32-bit-mex-file-not-working-in-a-64-bit-version-of-matlab). In addition, running a 32-bit version of MATLAB in a 64-bit environment can be problematic (see https://www.mathworks.com/matlabcentral/answers/101743-is-running-32-bit-matlab-on-a-64-bit-platform-supported). The best answer for .mexw32 files is to find a 64-bit replacement. If you own the source code, you can recompile the extension.
· .mexw64: 64-bit Windows
· .mlapp: Defines a MATLAB application created using the MATLAB App Designer, described in Chapter 14. A MATLAB application lets you share your code in a nicely packaged form with other people, and you can create one without having any programming experience (although a little experience does help).
The .mlapp file is actually a kind of .zip file, so you can open it using a file archiver to see what’s inside. This knowledge can come in handy when you need to use code found in a .mlapp file with an older version of MATLAB, as described at https://www.mathworks.com/matlabcentral/answers/404815-how-to-get-code-from-a-mlapp-file-using-an-earlier-matlab-version.
· .mlappinstall: Provides the means for installing a MATLAB application on another machine. Because an application can consist of several files, using an application installer makes the task of moving the application to another machine easier and less error prone. You can discover more about the packaging process in the “Packaging Your App” section of Chapter 14.
· .mlpkginstall: Accesses a MATLAB Hardware Support Package Installer, which provides support for various hardware devices within MATLAB. This is actually a type of XML file that describes how to install the hardware support you require. To use .mlpkginstall files, you must have a locally installed copy of MATLAB with a valid license. By default, newer copies of MATLAB ship with the Raspberry Pi Resource Monitor (see https://www.mathworks.com/help/supportpkg/raspberrypi/ug/raspberrypiresourcemonitor-app.html for details). Creating a package is outside the scope of this book, but you can learn how to build one at https://www.mathworks.com/matlabcentral/answers/395889-how-do-i-create-my-own-hardware-support-package.
· .mltbx: Allows distribution of MATLAB elements, such as code, data, apps, examples, and documentation, that are designed to work together to perform tasks such as analysis with greater ease. Mathworks provides a host of toolboxes for various tasks and you can also find other toolboxes developed by third parties online. The “Developing a Toolbox” section of Chapter 15 provides more information on creating a toolbox of your own.
· .mlx: Contains a Live Script or Live Function. These new ways of writing MATLAB code are a vast improvement over previous techniques because you can see the output in a nicely formatted presentation. The .mlx file is actually a kind of .zip file, so you can open it using a file archiver to see what’s inside. Chapter 11 tells you how to work with Live Scripts, while Chapter 12 tells you how to work with Live Functions.
· .p: Performs the same task as an .m file, except the content is protected from edits by anyone else. This feature lets you distribute your scripts to other people without fear of giving away programming techniques or trade secrets.
· .prj: Defines a MATLAB project. You can create a blank project, start with a folder of MATLAB elements, or obtain code from either Git or Apache Subversion (SVN). Other MATLAB tasks also rely on project files, such as when you create an application or an application installer.
· .slx: Contains a Simulink model. Simulink is an add-on product for MATLAB that provides a block diagram environment for performing simulations. You can read more about this product at https://www.mathworks.com/help/simulink/gs/product-description.html. This book doesn’t discuss the Simulink add-on because it’s an advanced product used for higher-end needs.
Exploring folders with the GUI
The GUI method of working with folders in MATLAB requires the Current Folder window shown in Figure 4-1. (To display this window, choose Layout ⇒ Current Folder in the Environment group of the Home tab.) In this case, the Current Folder toolbar appears at the top of the Current Folder window. You can also place it below the Toolstrip by choosing Layout ⇒ Current Folder Toolbar ⇒ Below Toolstrip in the Environment group of the Home tab. (The screenshots in the rest of the book assume that you have selected the Inside Current Folder option.)
FIGURE 4-1: The Current Folder window provides GUI access to the MATLAB folders.
The Current Folder toolbar shows the current folder that the Current Folder window displays. To change locations, simply type the new location in the field provided. You can also select a location by clicking the right-pointing arrow next to each level. The arrow changes to a down-pointing arrow, as shown in Figure 4-2, with a list of destinations below it. Clicking the magnifying glass icon in the field turns it into a Search field, where you can choose the kind of file you want to find.
FIGURE 4-2: You can choose new locations by clicking the right-pointing arrow.
The Current Folder toolbar also includes four buttons. Each of these buttons helps you move to another location on the hard drive, as follows:
· Back: Moves the location back one position in the history list. The history list is a list that is maintained by MATLAB that tracks the locations you’ve visited.
· Forward: Moves the location forward one position in the history list.
· Up One Level: Moves the location up to the parent folder.
· Browse for Folder: Displays a Select New Folder dialog box that you can then use to find another location on the hard drive. (See Figure 4-3.) After you find the folder, highlight its entry and click Select Folder to select it.
The Current Folder window provides access to all the folders that you’ve set up for organizational purposes. In this case, you see the Chapter02 subfolder (child folder) of the C:\MATLAB2 folder. The Chapter02 folder contains two files (refer to Figure 4-2). When you right-click the Chapter02 folder entry, you see a number of commands on a context menu like the one shown in Figure 4-4.
Note that not all the entries on the context menu have to do with exploring folders or managing them from a file structure perspective. The following list focuses on those commands that do help you manage the file structure.
· Open: Opens the folder so that it becomes the current folder in the Current Folder toolbar.
FIGURE 4-3: The Select New Folder dialog box helps you find other locations on the hard drive.
FIGURE 4-4: The context menu associated with a folder contains options for managing the folder content.
· Show in Explorer (Windows only): Opens a copy of Windows Explorer so that you can interact with the folder using this Windows tool.
· Create Zip File: Creates a new .zip file that contains the compressed content of the folder. This feature makes sending the folder to someone else easier.
· Rename: Changes the name of the folder.
· Delete: Removes the folder and its content from the hard drive. Depending on how you have your system configured, this option could permanently destroy any data found in the folder, so use it with care.
· New: A menu containing file and folder options.
· Folder: Creates a new child folder within the selected folder.
· Script: Creates a new script file.
· Live Script: Creates a new Live Script file.
· Function: Creates a new function file.
· Live Function: Creates a new Live Function file.
· Example: Creates a new example file.
· Class: Creates a new class file.
· Zip File: Creates an empty .zip file.
· Compare Against Selected Files/Folders: Compares the selected files or folders against each other. You select two files or folders to use this option by highlighting the primary file or folder first, then Ctrl+clicking the secondary file or folder next. This command only compares like items — two folders or two files of the same type.
· Compare Against: Matches the content of the selected folder against another folder and tells you about the differences.
· Cut: Marks the folder for removal from the hard drive and places a copy on the Clipboard. The folder is removed from its current location when you paste the copy in its new location.
· Copy: Places a copy of the folder and its content on the Clipboard so that you can paste copies of it in other locations.
· Paste: Places a copy of a folder or file and its content as found on the Clipboard in the location you indicate.
· Add to Path: Adds a folder, selected folders, or selected folders and subfolders to the path so that MATLAB can locate resources within them when the folder isn’t the current folder as described here:
· Selected Folders: Adds only the selected folders even if the folders contain subfolders. Because the subfolders aren’t part of the path, MATLAB won’t see resources they contain.
· Selected Folders and Subfolders: Adds both the selected folders and any subfolders these folders contain to the path.
· Indicate Files Not on Path: Displays folders and files that are on the path in bold when selected.
· Refresh: Verifies that the presentation of folders and files in the Current Folder window matches the actual content on the hard drive. Another application may have made modifications to the hard drive content, and with this command you can synchronize MATLAB with the physical device.
Exploring folders with commands
Many people prefer not to use the mouse. In this case, you can duplicate most of the GUI methods of interacting with the current folder using keyboard commands. The results of typing a command and pressing Enter appear in the Command Window. To see how this feature works, try the following steps. (Your folder structure may not look precisely like the one in the book, but you should see appropriate changes as you type the commands.)
1. Type cd \MATLAB2 and press Enter.
The Current Folder window changes to show the folder used for the book. The change directory, cd, command will always modify the location in the Current Folder window unless you’re already there. You may have to change the actual folder information to match your system if you chose not to create the directory structure described in earlier chapters. For example, you might need to type cd \Users\\MATLAB\Projects and press Enter instead (and if your path contains spaces, you must enclose the entire path in single quotes).
Even though you can’t see it in this black-and-white book, MATLAB does provide color coding to make working with commands easier. Notice that the command portion of a command is in black lettering, while the argument part of the command is in purple lettering. The use of color coding helps you better see the commands and how they’re structured.
2. Type mkdir Chapter04 and press Enter.
MATLAB creates a new folder in the Current Folder window to hold the materials for this chapter. Notice that you don’t include a backslash (or slash) when creating a child directory for the current directory.
If you’re using the downloadable source, you already have a Chapter04 folder in your MATLAB directory. Create a Chapter04a folder instead to hold the results of this and any other hands-on exercises in the chapter. Every place you see Chapter04, use Chapter04a instead.
3. Type cd Chapter04 and press Enter.
The directory changes to the one used for this chapter. Notice (again) that you don’t include a backslash (or slash) when moving to a subdirectory of the current directory.
4. Type copyfile ..\Chapter02\FirstScript.m and press Enter.
You see the copied file appear in the Current Folder window in the Chapter04 folder.
1. The copyfile command provides the functionality needed to copy a file.
2. The .. part of the path statement says to look in the parent folder, which is \MATLAB.
3. The Chapter02 part of the path says to look in the Chapter02 subdirectory, which equates to \MATLAB\Chapter02.
4. The FirstScript.m part of the path is the name of the file you want to copy to the current folder.
5. Type exist FirstScript.m and press Enter.
The command used in this case has a number of parts to it:
MATLAB provides an output value of 2, which means that the file exists. This final step helps you validate that the previous steps all worked as intended. If one of the previous steps had gone wrong, you’d see a failure indicator, such as an error message or a different output value (as shown in the next step), with this step.
6. Type exist MyScript.m and press Enter.
In this case, the output value of 0 tells you that MyScript.m doesn’t exist, as shown in Figure 4-5. The procedure didn’t tell you to create MyScript.m, so this output is completely expected.
Now that you can see how the commands work, it’s time to look at a command list. The following list contains an overview of the most commonly used file and folder management commands. (You can get detailed information at https://www.mathworks.com/help/matlab/file-operations.html.)
· cd: Changes directories to another location.
· copyfile: Copies the specified file or folder to another location.
· delete: Removes the specified file or object.
· dir: Outputs a list of the folder contents.
· exist: Determines whether a variable, function, folder, or class exists.
· fileattrib: Displays the file or directory attributes (such as whether the user can read or write to the file) when used without attribute arguments. Sets the file or directory attributes when used with arguments.
· isdir: Determines whether the input is a folder.
FIGURE 4-5: MATLAB not only allows you to manage the file structure but also to validate it using commands.
· ls: Outputs a list of the folder contents.
· mkdir: Creates a new directory.
· movefile: Moves the specified file or folder to another location.
· open: Opens the specified file using the default application. (Some files can be opened using multiple applications.)
· pwd: Displays the current path information, including the drive letter.
· recycle: Determines whether deleted files or folders are moved to the recycle bin.
· rmdir: Deletes the specified directory.
· type: Outputs the content of the specified file as text.
Some commands, such as type, can be combined with other commands, such as disp, to create well-formatted output. The disp command displays text, variables, or arrays. You discover how to use it later in the book (starting with Chapter 8). The point is that you sometimes combine commands to obtain a desired output.
· visdiff: Performs a comparison of two files or folders of the following types:
· what: Provides a categorized listing of MATLAB-specific files in the current directory. For example, if the current directory contains any files with an .m extension, you see them listed in the MATLAB code files category.
· which: Helps locate files and functions based on filename, function name path, or other criteria.
· winopen: Used only with Windows; opens the specified file using the default application. (Some files can be opened using multiple applications.)
Working with files in MATLAB
Folders provide organization, but files are what hold your data. Working with files is an essential part of learning to work with MATLAB. After all, if you can’t find your data, you can’t do anything with it. Managing the data to ensure that it remains safe, secure, and reliably accessible is important. The following sections describe how to perform common tasks with files.
Using the right-click to your advantage
Every file and folder shown in the Current Folder window has a context menu associated with it. A context menu always displays just the actions that you can perform with that file or folder. By right-clicking various files and folders, you see the context menu and might discover new tasks that you can perform with the file or folder you highlighted.
Right-clicking a file or folder can never damage it. The only time you might damage the file or folder is if you select an item from the context menu. To close the context menu after you view it, click in an empty area outside the context menu or press Escape.
Depending on your platform, you may also see shortcut keys when viewing the context menu. For example, when working with Windows, you can highlight a file and press Ctrl+C to copy it to the Clipboard — all without using the context menu at all. Pasting is just as easy: Select the folder you want to use to store the file and press Ctrl+V. As mentioned, these shortcut keys are platform specific, which is why they aren’t used in the book.
Copying and pasting
Copying and pasting creates a copy of an existing data file and places that copy in another location. You use this process in a number of ways. For example, you might want to make a backup of your data before you modify it or share the data with a friend. Even though the following steps use a specific file and locations, you can easily use them for any file you want to copy and paste and with any location. In this case, you copy FirstWorkspace.mat found in the Chapter02 folder to the Chapter04 folder (or Chapter04a if you’re using the alternative setup with the downloadable source).
1. Open the \MATLAB\Chapter02 folder in the Current Folder window.
You see two files: FirstScript.m and FirstWorkspace.mat.
2. Right-click FirstWorkspace.mat and choose Copy from the context menu.
This action copies the file onto the Clipboard. You won’t actually see anything happen in the window.
3. Click the Up One Level button in the Current Folder toolbar.
You return to the \MATLAB folder. This folder should show two subdirectories: Chapter02 and Chapter04, unless you’re working with the downloadable source, in which case you see all the folders for this book. If you don’t see both subdirectories, make sure to create the Chapter04 subdirectory using the steps found in the “Exploring folders with commands” section, earlier in this chapter.
The Chapter02 subdirectory is darker than the Chapter04 subdirectory, and the file folder appears open rather than closed. The reason for this difference is that the Chapter02 subdirectory is on your MATLAB path, while the Chapter04 subdirectory isn't. To add Chapter04 to the path, right-click its entry and choose Add To Path ⇒ Selected Folders or Add To Path ⇒ Selected Folders and Subfolders from the context menu.
4. Double-click the Chapter04 folder to open it.
This folder should contain a single existing file, FirstScript.m.
5. Right-click anywhere within the folder area and choose Paste.
MATLAB copies the file to the new location for you. At this point, the Chapter04 folder should look precisely like the Chapter02 folder.
Cutting and pasting
The process for cutting and pasting a file is almost the same as copying and pasting it. (See the previous section for details.) The only difference is that you select Cut rather than Copy from the context menu. However, the results are slightly different. When you cut and paste a file, the file is actually moved from one location to another. You use Cut and Paste when you don’t want to create multiple copies of a file and simply want to place the file in another location.
Dragging a file or folder moves it from one location to another. All you need to do is click the file. While you hold the mouse button down, you drag the file to a new location. MATLAB moves the file to the location you specify.
If the location already has a file with that name, MATLAB displays a message asking whether you’re sure you want to move the file. You must confirm the move before MATLAB performs the task. The new file replaces the existing file, so you could experience data loss.
Accessing and Sharing MATLAB Files
To make data useful, you need to be able to open the files containing it. Otherwise, there isn’t any point in saving the data. Likewise, not all your colleagues will have a copy of MATLAB, or they may want to use a different application to interact with the MATLAB data. For you to use their data, you must be able to import data files created by other applications. When you want to share your data with others, you must export your data to files that are understood by other applications. MATLAB provides great support for both imported and exported data.
The fastest way to open any MATLAB file is to double-click its entry in the folder found in the Current Folder window. You can also right-click the entry and choose Open from the context menu. MATLAB automatically opens the file using a default application or method.
It’s important to realize that MATLAB always uses a default application or method. Data files are sometimes associated with other applications. In addition, some data files can be opened in more than one way.
When you want to use an alternative method of opening a file, you must rely on the underlying platform. For example, when working with Windows, right-click the file and choose Show in Explorer from the context menu. A copy of Windows Explorer opens, and you can work with alternative applications in that copy. Right-click the file in Windows Explorer and choose one of the alternative applications shown in the Open With menu of the context menu. Figure 4-6 shows an example for FirstScript.m that presents several choices of application in which to open the file using (with the default shown at the top of the list).
FIGURE 4-6: Use a platform-specific means of opening files using alternative applications.
MATLAB also uses different techniques for interacting with files when you work with commands. The default action for a .mat file is to load it into MATLAB and execute it — showing the result in the Workspace window. However, you can either load it or open it, as needed. Here are the two commands you use (assuming that you want to work with FirstWorkspace.mat):
The first command actually opens the workspace so that you can see a result in the Command Window in addition to the Workspace window. However, the results aren’t loaded into the Workspace window as they normally would be if you double-clicked the file. To achieve this same effect, you must use the second command, which loads the workspace into MATLAB. Try loading FirstWorkspace.mat now so that you have a value in ans to use for the sections that follow.
You rely on commands to export data from MATLAB. The list of data formats at https://www.mathworks.com/help/matlab/import_export/supported-file-formats.html includes commands in the Export Function column for each format that MATLAB supports. To export the data in this section, you need to first open the FirstWorkspace.mat file using the technique found in the previous section.
Most of the commands work with a single variable. For example, if you want to export the information found in the ans variable (defined in the previous section as a double with the value 4) to a CSV file, you type something like csvwrite('FirstWorkspace.csv', ans). In this case, csvwrite() is the function, FirstWorkspace.csv is the name of the file, and ans is the name of the variable you want to export. Newer versions of MATLAB rely on writematrix() instead of csvwrite() (although both are supported). In this case, you type something like writematrix(ans, 'FirstWorkspace.csv'). Notice that the position of the variable, ans, is first in this case.
Along with csvwrite(), the most commonly used export commands are xlswrite(), which creates an Excel file, and dlmwrite(), which creates a delimited file. Both of these commands work much the same as csvwrite(). Note that newer versions of MATLAB use writetable(), writematrix(), or writecell() in place of these two older commands. The reason this chapter also covers the older commands is that you encounter them regularly in various places online and in existing code.
Some file formats require quite a bit of extra work. For example, to create an eXtensible Markup Language (XML) file, you must first build a document model for MATLAB to use. You can see the procedure for performing this task at https://www.mathworks.com/help/matlab/ref/xmlwrite.html.
MATLAB makes importing whatever data you need from an external source easy. To use the procedure in this section, you must create FirstWorkspace.csv using the technique found in the previous section. The following steps show you how to import any file using FirstWorkspace.csv as an example:
1. Click Import Data in the Variable group of the Home tab.
You see the Import Data dialog box. Note that MATLAB defaults to showing every file it can import.
If you find that the list of files is too long, you can click the Recognized Data Files drop-down list and choose just one of the common file types. The list displays just those files, making a selection easier.
2. Highlight the file you want to import and click Open.
The example assumes that you’re using FirstWorkspace.csv, but any file that MATLAB supports for import will work. MATLAB displays an Import dialog box that contains import information about the file, as shown in Figure 4-7. This dialog box contains settings that you use to import the data and ensure that it’s useful in MATLAB. Figure 4-7 shows the settings for a comma-separated value (CSV) file, and the rest of the procedure assumes that you’re working with such a file. However, the process is similar for other file types.
FIGURE 4-7: The Import dialog box lets you tweak the import settings.
3. (Optional) Modify the settings as needed so that the data appears as it should appear in the Workspace window.
You can choose to limit the amount of data imported by changing the range. You can also select a different delimiter (which changes how the data appears onscreen).
4. Verify that the Unimportable Cells group has no entries.
Cells that MATLAB can’t import might reflect an error or simply mean that you have some settings wrong.
5. Click Import Selection.
MATLAB imports the data using the Import Data option (the default) on the Import Selection drop-down list. As alternatives, you can also choose to generate a Live Script, script, or function based on the data, rather than actually import the data into the workspace.
6. Close the Import window.
Notice that the Workspace window includes entries for
· ans: Obtained by loading the FirstWorkspace.mat file
· FirstWorspace: Obtained by importing the data from FirstWorkspace.csv
You can read about the data formats that MATLAB can import at https://www.mathworks.com/help/matlab/import_export/supported-file-formats.html. This site also contains commands that you can use to import the files rather than relying on the GUI to do the work. However, the GUI is always faster and easier to use, so it’s the recommended course.
Saving Your Work
An essential part of ending any session with MATLAB is saving your work. Otherwise, you could lose everything you’ve worked so hard to achieve. In fact, smart users save relatively often to avoid the power-failure penalty. How often you save depends on your personal work habits, the value of the work, and the potential need to use time and system resources efficiently. No matter how you save, or when, the following sections help you get the job done.
Saving variables with the GUI
Although Chapter 2 does show you how to save the entire workspace, sometimes you need to save just one variable. You can perform this task using the GUI and the following steps:
1. Right-click the variable that you want to save in the Workspace window and choose Save As from the context menu.
You see the Save to MAT-File dialog box.
2. Type a name for the file in the File Name field.
Choose something that will help you remember the purpose of the variable.
You can use the tree structure in the left pane to choose a different folder if you don’t want to use the current folder to store the file containing the variable information.
3. Click Save.
MATLAB saves the variable to the file you choose.
Saving variables using commands
You can use commands to save your variables to disk. In fact, the command form is a little more flexible than the GUI. The basic command you use is save('filename'), where filename is the name of the file you want to use. Note that save() overwrites any existing file of the same name without telling you first.
When you want to save specific variables, you must add a list of them after the filename. For example, save('MyData.mat', 'ans') would save a variable named ans to a file named MyData.mat in the current folder. You can include path information as part of the filename if you want to save the data in a different folder. For example, save('C:\Temp\MyData.mat', 'ans') would save the data in the C:\Temp folder. If you want to save multiple variables, simply create a comma-delimited list of them. To save Var1 and Var2 to MyData.mat, you type save('MyData.mat', 'Var1', 'Var2').
These initial commands save the output in MATLAB format. However, you can also specify a format. The formats are listed at https://www.mathworks.com/help/matlab/ref/save.html#inputarg_fmt. For example, to save the previous variables in ASCII format, you type save('MyData.txt', 'Var1', 'Var2', '-ASCII').
Saving commands with the GUI
You can’t save commands that you type directly into the Command Window using the GUI. What you do instead is save them using the Command History window. The “Saving a formula or command as a script” section of Chapter 2 describes how to save both formulas and commands.
Saving commands using commands
MATLAB does let you save commands to disk using a command: diary. A diary is simply an on-disk record of the commands that you type in the Command Window. Recording starts when you start the diary — the resulting file doesn’t contain all the entries in the Command History window. Later, you can review the file and edit it just as you would a script. The diary command actually has a number of forms, as follows:
· diary: Creates a diary file with the filename diary. Because this file has no extension, it isn’t associated with anything. The output is ASCII, and you can open it with any text editor.
· diary('filename'): Creates a diary file that has the name filename. You can give the output file an .m extension, which means that you can open it as a script using the MATLAB editor. This approach is actually better than using diary by itself because the resulting file is easier to work with.
· diary off: Turns off recording of your commands so that they aren’t recorded to the file. Setting the diary to off lets you experiment before committing commands that you don’t want to the file on disk.
· diary on: Resumes recording of your commands.
Using online storage
Many individuals and organizations now use online storage facilities such as GitHub (https://github.com/) to store data. This makes it possible to use your data anywhere and from multiple devices. In addition, you can share data with any number of individuals who may need to collaborate with you. Using online storage means downloading and installing additional software, configuring it, and then using it to make a connection. The process for performing these steps is outside the scope of this book, but you can find a procedure for it at https://www.mathworks.com/help/matlab/matlab_prog/set-up-git-source-control.html.