VGUOL MSC PGMAT106 Matlab Unit 1.ebook
VGUOL MSC PGMAT106 Matlab Unit 1.ebook
Semester – I
MATLAB
Unit 1: Input output of data from MATLAB command. File types.
Creating, saving and executing the script file. Creating and
executing functions file. Working with files and directories.
Copyrights
We acknowledge the contributions of Subject matter experts, reviewers, and the content team
for successfully delivering this eBook. Due credits have been mentioned for
diagrams/Figures utilized to enrich the student content from open sources.
Preface
In this unit, we'll delve into crucial aspects of data input and output in MATLAB. You'll learn
to efficiently manage different file types, including script files, function files, and data files.
We'll explore the process of creating, saving, and executing script files, which is fundamental
for automating tasks and improving code readability. Additionally, we'll cover the creation
and execution of function files, enabling you to write modular and reusable code for your
MATLAB projects.
Managing files and directories plays a pivotal role in organizing your MATLAB workflow.
You'll gain insights into file navigation, directory creation, and various file manipulation
techniques. These skills are essential for streamlining your programming and data analysis
tasks, making you a more proficient MATLAB user. This unit equips you with the knowledge
and practical skills necessary to excel in MATLAB's data management and programming
capabilities.
Table of Content
Learning
Objectives………………………….…………………………………………
…………………………………………………….1
Introduction ....................................................................................................... 2
1.1 Input-Output of Data from MATLAB Command .................................... 3
1.2 File Types in MATLAB ........................................................................... 9
1.3 Creating, Saving, and Executing Script Files in MATLAB .................. 16
1.4 Creating and Executing Functions Files in MATLAB .......................... 20
1.5 Working with Files and Directories in MATLAB ................................. 24
1.6 Summary................................................................................................. 27
1.7 Review Questions ................................................................................... 28
1.8 Keywords................................................................................................ 29
1.9 References .............................................................................................. 30
Learning Objectives
After studying this unit, the student will be able to:
Understand the fundamentals of data input and output operations in MATLAB,
including reading and displaying data from the command line.
Learn about the different file types used in MATLAB, such as script files, function
files, and data files, and comprehend their respective roles.
Gain the ability to create, save, and execute script files to automate tasks and enhance
code readability in MATLAB.
Explore the creation and execution of function files, enabling modular and reusable
code development for more complex MATLAB projects.
Develop proficiency in working with files and directories, including file navigation,
directory creation, and file manipulation to efficiently manage resources within
MATLAB.
Master techniques for handling various file types, understanding their unique
characteristics and how they fit into the MATLAB workflow.
1
Introduction
MATLAB, a powerful computing environment, provides us with a vast array of tools and
techniques to manipulate and process data. Whether you're a beginner or an experienced
MATLAB user, understanding how to work with data, files, and directories is crucial for
efficient programming and data analysis.
In this unit, we will explore the fundamental concepts of data input and output in MATLAB.
You will learn how to read data from external sources and display information effectively
using MATLAB's command line interface.
File Types:
We'll delve into the different types of files essential in MATLAB, including script files,
function files, and data files. Each file type has a unique role, and understanding their
distinctions is crucial for effective MATLAB programming.
Script files are a core component of MATLAB programming. You will discover how to
create, save, and execute script files, allowing you to automate tasks, improve code
readability, and facilitate code reuse.
Functions are essential for modular and reusable code in MATLAB. We'll provide insights
into creating and executing function files, enabling you to write efficient and versatile code
for your MATLAB projects.
Effective file and directory management is pivotal for organizing your MATLAB workflow.
We will cover techniques for file navigation, directory creation, and file manipulation,
helping you maintain an organized and structured workspace.
2
By the end of this unit, you will have a deep understanding of MATLAB's input-output
capabilities, file handling, and resource management. These skills are vital for enhancing
your efficiency and productivity when working on various MATLAB projects.
In MATLAB, the ability to efficiently manage data input and output is a fundamental skill
for data analysis, script automation, and interaction with external files. Whether you're
dealing with numeric data, text, or complex data structures, MATLAB offers various
techniques to handle these operations.
Input in MATLAB:
Input in MATLAB refers to the process of providing data, values, or information to the
MATLAB program during its execution. This input can come from various sources,
including the user, external files, or other software components. MATLAB provides
several methods for handling input:
User Input: MATLAB allows interaction with users by accepting input from the
command window. The input function is a common choice. It prompts the user for input,
waits for a response, and stores the entered value in a variable. This is useful for scenarios
where user interaction is required to provide input data.
Example:
File Input: You can read data from external files in various formats, such as text, CSV,
or Excel files. Functions like load, csvread, and xlsread make it easy to import data into
MATLAB for analysis. This is especially valuable when working with large datasets or
data collected from different sources.
Example:
data = load('data.txt');
3
provided input and return results. This is a powerful way to create reusable and
parameterized code.
Example:
end
Example:
End
Input in MATLAB is a crucial component of any program, and it can originate from
various sources. Here are some common applications of input in MATLAB:
Displaying Data: MATLAB offers functions like disp and fprintf for displaying data
to the command window. The disp function is useful for basic text and numerical
output. fprintf provides more control over formatting, allowing you to create custom
messages.
Example:
5
disp('Hello, MATLAB!');
Saving Data: After performing calculations or data analysis, you can save the results
to various file formats. The save function is used to save workspace variables. fprintf
is employed for creating custom output files, where you can specify the format and
structure of the output.
Example:
save('results.mat', 'data');
Example:
x = 1:10;
y = x.^2;
plot(x, y);
File Output: When working with text files or other formats, MATLAB provides
functions like fscanf and fprintf for structured reading and writing of data. This is
crucial for data export and generating formatted reports.
Example:
fclose(fileID);
6
Custom Functions: You can create custom functions specifically for outputting
results. These functions can encapsulate the logic for creating reports, visualizations,
or any custom output required for your specific application.
Example:
function generate_report(results)
end
7
Versatility: MATLAB can seamlessly integrate with other software tools and
languages, allowing for data exchange and collaboration across different
platforms.
Scientific Publishing: MATLAB-generated figures and plots are commonly
used in scientific publications and research papers, underlining its credibility
in the scientific community.
Output in MATLAB is essential for conveying results, visualizing data, and generating
reports. Here are some common applications of output in MATLAB:
8
1.2 File Types in MATLAB
MATLAB supports various file types, each serving distinct roles in the data management
and analysis process. Understanding these file types is essential for efficient MATLAB
programming.
Script files are perhaps the most common in MATLAB. They are plain text files
with the extension ‘.m’.
These files contain a series of MATLAB commands and functions.
Script files allow you to automate tasks and perform a sequence of operations in a
structured manner.
Scripts are executed in the order they appear in the file.
9
a = 5;
b = 10;
result = a + b;
disp(result);
Application: Script files are widely used in MATLAB for task automation, exploratory
data analysis, and code prototyping. They are valuable for quickly performing a series of
operations or calculations.
Example: A MATLAB script can be used to process data files, generate plots, or perform
numerical simulations. It is particularly useful for one-time analysis tasks or interactive
exploration.
Function files are also ‘.m’ files, but they serve a different purpose.
Functions are more modular and allow for parameterized code that can be reused
in various parts of your MATLAB project.
They return values or perform specific operations based on input arguments.
Functions are called explicitly when needed.
result = a + b;
end
Application: Function files are essential for creating modular and reusable code in
MATLAB. They are used to encapsulate specific operations or calculations and can
accept input arguments, making them versatile.
10
Example: Functions can be applied in various domains, such as scientific simulations,
signal processing, or data modeling. For instance, you can create a function to calculate
statistical measures like mean and standard deviation for datasets.
Data files are used to store data, which can be numerical, text, or other structured
information.
MATLAB supports a range of data file formats, including text files (.txt),
Comma-Separated Values (CSV) files (.csv), Excel files (.xls, .xlsx), and more.
These files are used for importing data into MATLAB or exporting data for
external use.
Application: Data files are crucial for data import, export, and exchange between
MATLAB and other software. They facilitate data interoperability and help manage large
datasets efficiently.
Example: Data files can be used to import external data sources (e.g., sensor readings,
survey results) into MATLAB for analysis. After analysis, the results can be saved in data
files for sharing or further processing in other tools.
Live scripts are a newer feature in MATLAB, combining text, code, and
visualizations.
They are interactive and can include narrative explanations alongside code.
Live scripts are ideal for creating reports, documentation, or educational material.
These files can be published in various formats, such as HTML or PDF.
11
%% Simple Example
x = [1, 2, 3, 4];
y = x.^2;
plot(x, y);
Application: Live scripts are excellent for creating interactive reports, educational
materials, and documentation that combines code, results, and explanations. They offer a
dynamic way to present and share MATLAB code.
Example: Live scripts are widely used in teaching, research, and reporting. For instance,
a live script can be used to generate reports with code, visualizations, and explanations for
scientific experiments or data analysis projects.
MATLAB Figure files have the .fig extension and are used to save MATLAB
figures and plots.
These files preserve the appearance and properties of a MATLAB figure,
allowing you to reopen and edit the figure later.
MATLAB figures can be saved as .fig files for further modification or sharing
with others.
% Create a plot
x = 1:10;
y = x.^2;
plot(x, y);
saveas(gcf, 'my_plot.fig');
12
Application: MATLAB Figure files are used for preserving and sharing plots and
visualizations created in MATLAB. They ensure that the appearance and properties of
figures remain consistent.
Example: Researchers and engineers often save MATLAB figures as .fig files to
maintain high-quality graphics for publications, presentations, and collaborative work.
MATLAB P-Code files have the .p extension and are used for protecting
MATLAB code.
P-Code files are encrypted versions of MATLAB scripts and functions, making it
difficult to view or modify the source code.
These files are often used when you want to share your MATLAB code while
protecting your intellectual property.
% Create a script
disp('Hello, MATLAB!');
pcode my_script.m
Application: P-Code files are used to protect the source code of MATLAB scripts and
functions. They are useful when you want to share code while safeguarding intellectual
property.
Example: Companies and individuals may use P-Code files to distribute proprietary
MATLAB code, algorithms, or applications without revealing the underlying code logic.
MATLAB Publish files are created from live scripts (.mlx) or script files and can
be published to various formats, such as HTML, PDF, or LaTeX.
These files contain both code and formatted output, making them suitable for
creating interactive documentation or reports.
13
MATLAB Publish is a valuable tool for generating professional reports that
include code, results, and explanations.
x = 1:10;
y = x.^2;
plot(x, y);
Application: Publish files are used to create professional reports and documentation that
include code, results, and explanations. They are ideal for generating interactive and well-
structured documents.
Example: Academics, data scientists, and engineers use MATLAB Publish to create
research reports, tutorials, and user manuals. These files are suitable for documenting
complex analyses and simulations.
A script file in MATLAB is a plain text file with the file extension ‘.m’. It is a type of
MATLAB file that contains a sequence of MATLAB commands and functions. Unlike
functions, which can accept input arguments and return values, script files are primarily used
for task automation, data analysis, and executing a series of operations in a specific order.
Script files do not accept input arguments, making them suitable for quick prototyping,
exploration, and automating repetitive tasks.
14
Fig – Matlab Script Files
Script files are an integral part of MATLAB programming, allowing users to write, organize,
and execute code efficiently. They are particularly useful for creating code that performs a
set of actions, calculations, or data manipulations in a specific sequence.
a = 5;
b = 10;
result = a + b;
disp(result);
15
Saving a Script File:
After writing your MATLAB code in the script editor, you should save it for
future use.
To save a script file, click on the disk icon or use the "Save" option from the
"File" menu.
Choose a suitable location and provide a meaningful name with the .m
extension.
Saving the script allows you to reuse and edit it later.
Save sum_script.m
run sum_script.m
MATLAB will execute the commands in the script sequentially, and any results or
output will be displayed in the Command Window.
Code Organization: Script files allow you to organize your MATLAB code
into manageable units. You can group related code into separate scripts, making
it easier to maintain and understand your projects.
Reusability: Once a script is created, you can reuse it multiple times. This is
particularly useful for tasks that you need to perform regularly, such as data
preprocessing or visualization.
Documentation: Script files can serve as documentation for your code. By
including comments and explanations, you create a record of the steps and
processes involved in your analysis or application.
16
Debugging: Script files provide a structured environment for debugging. You
can isolate and test specific sections of your code, making it easier to identify
and correct errors.
Advantages: Script files are invaluable for data preprocessing tasks. You can
create a script that loads raw data, cleans it, and prepares it for analysis. This
script can be reused with different datasets, saving time and ensuring
consistency in data preparation.
Example: A script for data preprocessing might involve loading a CSV file,
removing missing values, standardizing variables, and saving the cleaned
dataset for further analysis.
Advantages: Script files are excellent for generating data visualizations. You
can create scripts to produce various types of plots and graphs. These scripts are
useful for producing publication-quality figures.
Example: A script for data visualization could generate a series of bar plots,
line charts, and scatter plots to illustrate trends and relationships in a dataset.
Advantages: Script files are essential for numerical simulations and modeling.
You can implement complex mathematical models and run simulations using
script files.
Example: A script for a numerical simulation might simulate the behavior of a
physical system over time, applying differential equations or other mathematical
models.
Advantages: Script files can be used for automated testing and quality control.
You can create scripts that test your code for correctness, accuracy, and
performance.
17
Example: A script for automated testing might apply a battery of test cases to
your functions and report any failures or deviations from expected behavior.
By leveraging script files in MATLAB, you can efficiently manage and execute various
tasks in data analysis, data science, engineering, and scientific research. These files
enhance code organization, reusability, and documentation while enabling you to tackle
a wide range of real-world applications.
Creating and executing function files in MATLAB is an essential part of the programming
process. Functions allow you to modularize your code, promote reusability, and improve
code organization. Let's dive deep into creating and executing function files in MATLAB:
Defining a Function:
Function files are created to perform specific tasks or computations. They accept
input arguments and return results.
To define a function, open the MATLAB script editor or any text editor and create a
new file with a .m extension.
Start with a function declaration, including the keyword function, the output
variables, and the input arguments.
Inside the function, write the code that performs the desired calculations or
operations.
Use the input arguments within the function to manipulate data and produce the
output.
18
area = length * width;
Calling a Function:
To use a function in MATLAB, you call it within a script, another function, or the
Command Window.
Use the function name followed by parentheses and provide the required input
arguments.
length = 5;
width = 3;
To execute the script or function that calls your custom function, you can run the
script directly or call the function from the Command Window.
19
Example of running a script that calls the function:
run my_script.m
By creating and executing function files in MATLAB, you can encapsulate specific
functionalities, enhance code readability, and build a library of reusable functions to
streamline your data analysis and programming tasks. Functions promote modularity and
efficiency in MATLAB programming.
20
Real Applications and Examples:
Scientific Computing:
o Application: Scientific researchers use functions for simulations and data
analysis.
o Example: A physics researcher may create a function to calculate the
trajectory of a projectile based on initial conditions.
Engineering:
o Application: Engineers use functions for signal processing, control systems,
and simulations.
o Example: An electrical engineer may develop a function to filter noise from
sensor data in a control system.
Data Analysis and Statistics:
o Application: Data analysts use functions for data cleaning, transformation,
and statistical analysis.
o Example: A data analyst can create a function to compute summary statistics
or perform regression analysis on a dataset.
Finance and Economics:
o Application: Financial analysts use functions for portfolio optimization, risk
assessment, and financial modeling.
o Example: A financial analyst may develop a function to calculate the Net
Present Value (NPV) of cash flows.
Image Processing:
o Application: Image processing professionals use functions for image
enhancement, segmentation, and feature extraction.
o Example: An image processing specialist may create a function to detect
edges in photographs.
Machine Learning and AI:
o Application: Machine learning practitioners use functions for model
training, evaluation, and feature engineering.
o Example: A machine learning engineer can write functions to preprocess
data, train a neural network, and assess its performance.
Biomedical Research:
21
o Application: Biomedical researchers use functions for data analysis, image
processing, and modeling.
o Example: A researcher in medical imaging may create a function to analyze
MRI images and extract relevant features.
By utilizing the advantages of function files and applying them to real-world applications,
MATLAB users can streamline their work, improve code quality, and achieve greater
efficiency in various domains, from scientific research to engineering and data analysis.
Working with files and directories in MATLAB is an essential aspect of data management,
code organization, and data analysis. Let's explore how to work with files and directories in
MATLAB:
Current Directory:
The current directory in MATLAB is the location where MATLAB looks for files
by default. You can check the current directory using the pwd command.
To change the current directory, use the cd command followed by the desired
directory path.
Example:
currentDir = pwd;
newDir = 'C:\Users\YourUsername\Documents';
cd(newDir);
Application: When loading or saving files in MATLAB, specifying relative paths based on
the current directory can simplify file handling in your scripts.
22
The dir command returns a structure array containing information about files and
directories in the specified location.
Example:
fileData = dir;
Application: Listing files in a directory is useful for batch processing or data import, where
you need to analyze or process multiple files.
Creating Directories:
To create a new directory, use the mkdir command followed by the directory name.
Example:
mkdir('Data');
Application: Creating directories is helpful for storing project-specific data, like raw data,
processed data, and results, in an organized manner.
sourceFile = 'my_data.xlsx';
destinationFolder = 'Data';
movefile(sourceFile, destinationFolder);
Application: Moving and copying files are common tasks in data preprocessing, where you
may want to store original data separately from processed data.
23
Deleting Files and Directories:
To delete files, use the delete command followed by the file name or path.
To delete directories, use the rmdir command followed by the directory name.
delete('obsolete_data.mat');
Application: File cleanup and management, especially in cases where outdated or temporary
files need to be removed to save storage space.
fclose(fileID);
Application: Reading data from text, Excel, or other file formats is common in data analysis
and manipulation tasks. Using the appropriate file functions can simplify these operations.
Working with files and directories in MATLAB is crucial for managing data, organizing
code, and automating file-related tasks. These operations facilitate data access, data storage,
and efficient data analysis in MATLAB.
1.6Summary
In MATLAB, working with files and data is fundamental for managing, processing, and
automating various tasks. Here's a summary of the key aspects related to this topic:
24
Input and Output of Data from MATLAB Command:
MATLAB offers versatile tools for importing and exporting data in various formats,
including text, spreadsheets, and more.
This capability is crucial for data analysis, as it enables data loading and saving
operations with ease.
File Types:
Understanding different file types, such as script files, function files, and data files, is
essential for effective programming and data management.
MATLAB supports a wide range of file types, each serving a unique purpose in the
programming workflow.
Script files are used to automate tasks, perform calculations, and execute a series of
commands.
Creating, saving, and executing script files allows for efficient code organization and
execution.
Managing files and directories within MATLAB involves tasks such as changing the
current directory, listing files and directories, creating, moving, copying, and deleting
files, and performing file and directory operations.
These operations are vital for organizing data, automating tasks, and ensuring
efficient data access.
25
1.7 Review Questions
1. What is the significance of understanding file types in MATLAB, and how can it
benefit your programming workflow?
2. Explain the process of changing the current directory in MATLAB and provide an
example scenario where this might be useful?
3. How do script files differ from function files in MATLAB, and what are the
advantages of using each type?
4. Describe the steps involved in creating, saving, and executing a script file in
MATLAB. Why are script files essential in programming?
5. What are function files in MATLAB, and how do they facilitate code organization
and reusability? Provide an example of a situation where a function file would be
beneficial.
6. How can you list files and directories in the current directory in MATLAB using
the dir command, and what information does the command provide?
7. Explain the process of creating a new directory in MATLAB using the mkdir
command and describe a practical scenario where this action is necessary?
8. Discuss the methods for moving and copying files in MATLAB, and provide an
example use case for both operations?
9. When working with files and directories, what is the purpose of the fileparts
function in MATLAB, and how can it be applied?
10. Why is understanding and effectively working with files and directories important
in data analysis and project management using MATLAB?
1.8 Keywords
File Types: File formats supported in MATLAB for storing and managing data and
code.
Current Directory: The directory in MATLAB where it searches for files and stores
newly created files by default.
Script Files: Files in MATLAB that automate tasks by executing a series of
commands.
Function Files: MATLAB files designed to encapsulate specific functionalities and
promote code modularity.
Creating and Saving: The process of creating and saving files in MATLAB for data
and code management.
26
Executing Scripts: Running script files to automate tasks and calculations in a
specific order.
Working with Directories: Managing directories in MATLAB for efficient data
organization and storage.
Listing Files: Using the dir command to obtain a list of files and directories in a
specified location.
Creating Directories: The action of creating new folders in MATLAB to organize
data and code.
Moving and Copying Files: Relocating or duplicating files between directories using
MATLAB commands.
Deleting Files and Directories: Removing unwanted files or directories to free up
storage space.
File Operations: Functions and commands for reading, writing, and checking file
properties in MATLAB.
File Path Manipulation: Functions like fileparts used for extracting components of
file paths.
Data Import and Export: Procedures for transferring data between MATLAB and
external files in various formats.
Data Organization: Techniques for organizing and managing data within MATLAB
for effective data analysis.
1.9References
1. Getting Started with MATLAB 7: Rudra Pratap; Oxford Press.
2. Applied Numerical Methods using MATLAB: Won Young Yang, Tae-Sang-
Chung, John Morris: John Wiley and Sons.
3. Solving ODE’s with MATLAB: L.F. Shampine, I Gladwell, S. Thompson;
Cambridge University Press.
27