0% found this document useful (0 votes)
8 views

VGUOL MSC PGMAT106 Matlab Unit 1.ebook

Pg matlab

Uploaded by

saisahi17294
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

VGUOL MSC PGMAT106 Matlab Unit 1.ebook

Pg matlab

Uploaded by

saisahi17294
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 32

Master of Science

Semester – I

Course Code PGMAT106

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

Copyright © 2022 Vivekananda Global University

All rights reserved


Acknowledgment

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.

Input-Output of Data from MATLAB Command:

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.

Creating, Saving, and Executing Script Files:

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.

Creating and Executing Function Files:

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.

Working with Files and Directories:

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.

1.1 Input-Output of Data from MATLAB Command

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:

user_input = input('Enter a value: ');

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');

Parameterized Functions: MATLAB supports custom functions that take input


parameters. These functions can perform calculations or operations based on the

3
provided input and return results. This is a powerful way to create reusable and
parameterized code.

Example:

function result = calculate_area(length, width)

result = length * width;

end

Command-Line Arguments: MATLAB allows you to accept command-line


arguments when invoking a script or function. These arguments can be accessed
within your code, providing flexibility in handling external input.

Example:

function main(arg1, arg2)

% Access arg1 and arg2 here

End

Advantages and Characteristics of Input in MATLAB

 Flexibility: MATLAB provides flexibility in handling various types of input


data, including numeric values, text, and complex data structures, making it
versatile for different applications.
 Interactivity: Input in MATLAB allows for user interaction during program
execution. This interactivity is useful for customization and user-driven
decision-making.
 Data Integration: MATLAB seamlessly integrates with external data sources
and file formats, enabling the import and processing of data from diverse
origins.
 Customization: MATLAB empowers users to create custom input prompts
and functions, tailored to specific project requirements.
 Automation: MATLAB's input capabilities are efficient for automating data
acquisition and user interactions, streamlining repetitive tasks and enhancing
productivity.
4
 Modularity: Custom functions and scripts can be used for code modularity,
enabling organized and reusable code components.
 Efficiency: MATLAB is known for its efficiency in handling large datasets,
automating data processes, and optimizing data analysis workflows.

Applications of input in MATLAB

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:

 User Interaction: MATLAB often requires user input for customization or


decision-making. For example, in scientific simulations, user input may define
simulation parameters or initial conditions.
 Data Import: MATLAB frequently deals with external data. You might
import data from sensors, data loggers, or other applications. For instance, in
scientific experiments, you can import measurement data for analysis.
 File Processing: Many MATLAB programs process data from files such as
spreadsheets, text files, or databases. Applications include data preprocessing,
data mining, and data cleansing.
 Automated Data Acquisition: In industrial settings, MATLAB can be used to
automate data acquisition systems that collect data from various sensors and
devices.
 Signal Processing: MATLAB is widely used in signal processing applications,
such as audio and image processing, where data input comes from signal
sources.
 Output in MATLAB

Output in MATLAB involves displaying, saving, or conveying the results of computations,


data analysis, or other operations. MATLAB provides several methods for handling output:

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!');

fprintf('The result is: %f\n', result);

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');

fprintf('The final value is: %f\n', final_value);

Plotting and Visualization: MATLAB is renowned for its visualization capabilities.


Functions like plot, bar, and histogram are commonly used for creating plots, charts,
and graphs. This is essential for conveying complex data in a visual format.

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:

fileID = fopen('report.txt', 'w');

fprintf(fileID, 'Summary of results:\n');

fprintf(fileID, 'Value 1: %f\n', value1);

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)

% Code to generate a detailed report

end

Understanding how to effectively manage input and output in MATLAB is


fundamental for data analysis, automation, and creating well-structured and
informative MATLAB scripts. It is a skill that enables MATLAB users to interact
with data and users efficiently.

Advantages and Characteristics of Output in MATLAB

 Visualization: MATLAB excels in data visualization, allowing users to


generate high-quality plots, charts, and graphs for effective data presentation.
 Customization: MATLAB provides control over formatting and layout when
creating output, making it adaptable to various reporting and presentation
needs.
 Data Export: You can save results in multiple file formats, such as
spreadsheets, images, and text reports, catering to diverse data sharing and
reporting requirements.
 Automation: MATLAB is proficient in automating report and document
generation, saving time and effort in producing consistent and informative
documents.
 Error Handling: Robust error handling mechanisms, including the try-catch
construct, ensure that errors and exceptions are managed gracefully,
improving program reliability.
 Cross-Disciplinary Use: MATLAB's output capabilities make it suitable for
use in a wide range of fields, including engineering, finance, science, and data
analysis.

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.

Applications of output in MATLAB

Output in MATLAB is essential for conveying results, visualizing data, and generating
reports. Here are some common applications of output in MATLAB:

 Data Visualization: MATLAB excels in data visualization. It is used


extensively in fields like engineering, science, and finance for generating plots,
charts, and graphs to visually represent data.
 Automated Reporting: MATLAB can automatically generate reports,
presentations, or documents with embedded plots and analysis results. This is
valuable in research and data-driven decision-making.
 Debugging and Logging: In software development, MATLAB can produce
output logs for debugging purposes, helping developers identify and resolve
issues in their code.
 Data Export: MATLAB is often used to save analysis results in various
formats, including spreadsheets, images, and text reports.
 Simulation and Modeling: MATLAB generates output data in simulation and
modeling scenarios, which can be used for decision-making or further analysis.
 Feedback Control: In engineering and control systems, MATLAB can
provide real-time feedback through graphical interfaces, helping operators
make informed decisions.
 Educational Tools: MATLAB is a popular tool in academia for generating
educational materials, including slides, worksheets, and lab exercises.
 Scientific Publishing: MATLAB-generated figures and plots are frequently
used in scientific publications and research papers.

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.

Fig – MATLAB File Types

The primary file types in MATLAB are:

Script Files (‘.m’):

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

Example of a simple script file:

% This is a MATLAB script

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 (‘.m’):

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

Example of a simple function file:

% This is a MATLAB function

function result = add(a, b)

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 (Various Formats):

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

Example of a simple text data file:

Name, Age, Salary

John, 30, 50000

Mary, 28, 48000

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.

MATLAB Live Scripts (.mlx)

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

Example of a simple live script:

11
%% Simple Example

% This is a live script with code and explanations.

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 (‘.fig’)

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

Example of saving a MATLAB figure as a .fig file:

% Create a plot

x = 1:10;

y = x.^2;

plot(x, y);

% Save the figure as a .fig file

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 (‘.p’)

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

Example of generating a P-Code file from a MATLAB script:

% Create a script

disp('Hello, MATLAB!');

% Generate a P-Code file

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 (.html, .pdf, etc.)

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

Example of publishing a live script to HTML:

%% My MATLAB Live Script

% This is a live script with code and explanations.

x = 1:10;

y = x.^2;

plot(x, y);

% Publish the live script to HTML

publish('my_live_script.mlx', 'format', 'html');

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.

1.3 Creating, Saving, and Executing Script Files in MATLAB

Script File in MATLAB:

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.

 Creating a Script File:


 A script file in MATLAB is a plain text file with the extension .m.
 To create a script file, you can use the MATLAB built-in editor or any text
editor of your choice.
 In MATLAB, select "New Script" from the "File" menu to open a new script
editor window.
 You can then write and edit your MATLAB code within this editor.

Example of creating a simple script to calculate the sum of two numbers:

% This is a simple MATLAB script

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.

Example of saving a script as "sum_script.m":

Save sum_script.m

 Executing a Script File:


 Once a script is saved, you can execute it by running the script.
 To run a script, you can click the "Run" button in the script editor or use the run
command in the MATLAB Command Window.

Example of executing the "sum_script.m" script:

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.

Advantages of Creating, Saving, and Executing Script Files:

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

Applications and Examples:

Application: Data Preprocessing

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

Application: Data Visualization

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

Application: Numerical Simulations

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

Application: Automated Testing

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

1.4 Creating and Executing Functions Files in MATLAB

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:

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

Example of a simple function that calculates the area of a rectangle:

function area = calculate_rectangle_area(length, width)

Writing the Function Body:

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

Continuing the example:

% Calculate the area

18
area = length * width;

Saving the Function File:

 Save the function file with a meaningful name, such as calculate_rectangle_area.m.


 Save it in a directory that is part of MATLAB's search path or provide the full file
path when calling the function.

 Executing Function Files in MATLAB:

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.

Example of calling the calculate_rectangle_area function in a script:

length = 5;

width = 3;

area = calculate_rectangle_area(length, width);

Displaying or Using Function Outputs:

 Functions can return one or more output variables.


 You can display the results using the disp function or assign them to variables for
further use.

Example of displaying the area:

disp(['The area of the rectangle is: ' num2str(area)]);

Running the Script or Function:

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

Advantages of Creating and Executing Function Files in MATLAB:

 Modularity and Reusability:


o Advantage: Functions allow you to break down complex tasks into smaller,
manageable pieces of code.
o Example: You can create a function for data preprocessing, another for
feature extraction, and reuse them across multiple projects.
 Code Organization:
o Advantage: Functions help organize your code by separating tasks into
individual files, making it easier to maintain and debug.
o Example: Functions enable you to keep your main script or program clean
and focused on high-level logic.
 Parameterization:
o Advantage: Functions can accept input arguments, making your code
adaptable to different scenarios.
o Example: You can create a function for sorting data and specify the sorting
criteria as an argument.
 Error Isolation:
o Advantage: Functions help isolate errors, making it easier to identify and fix
issues in specific parts of your code.
o Example: If an error occurs in a function, you can focus on debugging that
function without affecting the entire program.
 Collaboration:
o Advantage: Functions facilitate collaboration among team members by
allowing them to work on different functions simultaneously.
o Example: A team of data scientists can each work on separate functions for
data preprocessing, model training, and evaluation.

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.

1.5 Working with Files and Directories in MATLAB

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:

% Check the current directory

currentDir = pwd;

% Change the current directory

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.

 Listing Files and Directories:


 You can list the files and subdirectories in the current directory using the dir
command.

22
 The dir command returns a structure array containing information about files and
directories in the specified location.

Example:

% List files and directories in the current folder

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:

% Create a new directory named 'Data'

mkdir('Data');

Application: Creating directories is helpful for storing project-specific data, like raw data,
processed data, and results, in an organized manner.

 Moving and Copying Files:


 You can move or copy files from one directory to another using the movefile and
copyfile commands.
 Specify the source and destination paths to move or copy files.

Example of moving a file:

% Move a file from the current directory to a subdirectory

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.

Example of deleting a file:

% Delete a file from the current directory

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.

 File and Directory Operations:


 MATLAB provides various functions for file operations, such as reading and writing
data files, accessing file information, and checking for file existence.
 Use functions like fopen, fclose, fread, fwrite, fileparts, and exist to work with files
and directories efficiently.

Example of reading data from a text file:

% Open and read data from a text file

fileID = fopen('data.txt', 'r');

data = textscan(fileID, '%f %f', 'Delimiter', ',');

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.

Creating, Saving, and Executing Script Files:

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

Creating and Executing Function Files:

 Function files in MATLAB encapsulate specific functionalities, enhance code


modularity, and promote code reuse.
 Creating and executing function files aids in task modularization and code
organization.

Working with Files and Directories:

 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

You might also like