0% found this document useful (0 votes)
3 views41 pages

Chapter 1 Matlab

The document outlines a course titled 'MATLAB Foundations' designed for first-year engineering students to develop programming skills and algorithmic thinking using MATLAB. It emphasizes an intuitive learning approach with practical exercises and covers various topics including MATLAB language, graphical representations, and GUI creation. The course aims to equip students with essential computational skills for future studies in engineering and scientific computing.
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)
3 views41 pages

Chapter 1 Matlab

The document outlines a course titled 'MATLAB Foundations' designed for first-year engineering students to develop programming skills and algorithmic thinking using MATLAB. It emphasizes an intuitive learning approach with practical exercises and covers various topics including MATLAB language, graphical representations, and GUI creation. The course aims to equip students with essential computational skills for future studies in engineering and scientific computing.
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

People’s Democratic Republic of Algeria

Ministry of Higher Education and Scientific Research


Ecole Nationale Polytechnique – Malek Bennabi – Constantine

MATLAB Foundations
A Computational Environment for Future Engineers

Dr. Mohamed Hachem Kermani


[Link]@[Link]

2025
Preface

The ability to translate real-world problems into computational solutions has become an
essential skill for engineers and scientists in the modern era. As technology advances and
data-driven decision-making becomes a cornerstone of industry and research, the need for
strong programming foundations has never been greater.

This course, MATLAB Foundations, was developed with a clear pedagogical goal:
to provide students with both the theoretical knowledge and practical skills required to ap-
proach problems algorithmically. MATLAB has been chosen as the primary tool because of
its simplicity, versatility, and powerful features for numerical computation, visualization,
and algorithm development.

Unlike traditional programming languages that may present a steep learning curve,
MATLAB offers an intuitive environment that enables students to focus on problem-
solving rather than low-level syntax. Throughout this course, students will progress from
the fundamentals of MATLAB’s interface and basic instructions to the implementation of
control structures, loops, and advanced operations on vectors and matrices.

The structure of this material reflects a gradual learning approach. Each chapter intro-
duces new concepts, supported by clear explanations, step-by-step examples, and carefully
designed exercises. Emphasis is placed on active learning and hands-on practice, as pro-
gramming can only be mastered through application.

This work is intended for first-year engineering students, but it is also suitable for
anyone beginning their journey in computational sciences. By the end of the course,
learners will not only acquire programming skills but also develop a systematic way of
thinking that will serve as a foundation for more advanced studies in engineering, data
analysis, and scientific computing.
Contents

Introduction 1

1 MATLAB Language 3
1.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.2 MATLAB Interface: Two Modes of Use . . . . . . . . . . . . . . . . . . . . 4
1.2.1 Command Window Mode . . . . . . . . . . . . . . . . . . . . . . . 4
1.2.2 Script Mode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
1.3 Variables and Constants . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
1.4 Basic Instructions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
1.4.1 Input/Output Instructions . . . . . . . . . . . . . . . . . . . . . . . 8
1.4.2 Assignment Instructions . . . . . . . . . . . . . . . . . . . . . . . . 10
1.4.3 Increment and Decrement Operations . . . . . . . . . . . . . . . . . 13
1.4.4 Practical exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
1.5 Conditional Structures in MATLAB . . . . . . . . . . . . . . . . . . . . . . 16
1.5.1 General Form . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
1.5.2 Alternative Conditional Structures . . . . . . . . . . . . . . . . . . 17
1.5.3 Comparison and Logical Operators in MATLAB . . . . . . . . . . . 19
1.5.4 Real-World Applications of Conditional Structures . . . . . . . . . 19
1.5.5 Practical Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
1.6 Iterative Structures in MATLAB . . . . . . . . . . . . . . . . . . . . . . . 20
1.6.1 While Loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
1.6.2 For Loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
1.6.3 While vs For Loop . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
1.6.4 Real-World Applications of Loops in MATLAB . . . . . . . . . . . 24
1.6.5 Practical Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
1.7 Complex Structures: Vectors & Matrices . . . . . . . . . . . . . . . . . . . 25
1.7.1 Definition and Types of Vectors . . . . . . . . . . . . . . . . . . . . 25
1.7.2 Matrix Definition . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
1.7.3 Accessing Elements . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
1.7.4 Creating Vectors with Operators . . . . . . . . . . . . . . . . . . . 27
1.7.5 Basic Operations on Vectors and Matrices . . . . . . . . . . . . . . 27
1.7.6 Common Functions for Vectors and Matrices . . . . . . . . . . . . . 28
1.7.7 Matrix Transpose and Inverse . . . . . . . . . . . . . . . . . . . . . 28
1.7.8 Element-wise Operations . . . . . . . . . . . . . . . . . . . . . . . . 28
1.7.9 Advanced Operations and Real-World Applications . . . . . . . . . 29
1.7.10 Practical Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
1.8 Procedures and Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
1.8.1 Procedures in MATLAB (Scripts) . . . . . . . . . . . . . . . . . . . 30
1.8.2 Functions in MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . 31
1.8.3 Predefined Functions in MATLAB . . . . . . . . . . . . . . . . . . 33
1.8.4 Comparison: Scripts vs Functions . . . . . . . . . . . . . . . . . . . 34
1.8.5 Practical Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
1.9 Tutorials . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
1.9.1 Tutorial 1: MATLAB language . . . . . . . . . . . . . . . . . . . . 36
1.9.2 Tutorial 2: Conditional Structures . . . . . . . . . . . . . . . . . . . 38
1.9.3 Tutorial 3: Vectors and Matrices . . . . . . . . . . . . . . . . . . . 41
1.9.4 Tutorial 4: Procedures and Functions . . . . . . . . . . . . . . . . . 43

2 Graphical Representations in MATLAB (2D and 3D) 45


2.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
2.2 Creating 2D charts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
2.2.1 Basic Plot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
2.2.2 Customizing 2D charts . . . . . . . . . . . . . . . . . . . . . . . . . 48
2.2.3 Multiple Curves in One Figure . . . . . . . . . . . . . . . . . . . . . 52
2.2.4 Subplots . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
2.2.5 Bar and Pie Charts . . . . . . . . . . . . . . . . . . . . . . . . . . . 55
2.2.6 Animated 2D Curves . . . . . . . . . . . . . . . . . . . . . . . . . . 58
2.3 Creating 3D Charts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
2.3.1 Basic 3D Plot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
2.3.2 Surface Plots . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60
2.3.3 3D Contour Plots . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62
2.3.4 3D Bar Charts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63
2.4 Tutorials: Exercises on 2D and 3D Plots . . . . . . . . . . . . . . . . . . . 64

3 Creating Graphical Interfaces in MATLAB 68


3.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68
3.2 Creating GUIs with GUIDE . . . . . . . . . . . . . . . . . . . . . . . . . . 69
3.2.1 Creating a GUI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
3.3 Creating GUIs through Programmatic Approach . . . . . . . . . . . . . . . 74
3.3.1 Creating a Window . . . . . . . . . . . . . . . . . . . . . . . . . . . 74
3.3.2 Adding Controls . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
3.3.3 Handling Events (Callbacks) . . . . . . . . . . . . . . . . . . . . . . 76
3.4 Advanced GUI Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79
3.4.1 Sharing Data Between Callbacks . . . . . . . . . . . . . . . . . . . 79
3.4.2 Dynamic Updates . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80
3.4.3 Summary of uicontrol Syntax . . . . . . . . . . . . . . . . . . . . 80
3.5 Creating Interactive Applications with App Designer . . . . . . . . . . . . 82
3.5.1 Key Features of App Designer . . . . . . . . . . . . . . . . . . . . . 82
3.5.2 Starting App Designer . . . . . . . . . . . . . . . . . . . . . . . . . 83
3.5.3 Creating a Simple App: Temperature Converter . . . . . . . . . . . 83
3.5.4 Running the App . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
3.5.5 Exporting and Sharing the App . . . . . . . . . . . . . . . . . . . . 86
3.5.6 Extended Example: Sine Wave Plotting App . . . . . . . . . . . . . 86
3.5.7 Advanced Components and Functionalities . . . . . . . . . . . . . . 87
3.5.8 Practical Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . 87
3.5.9 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87
3.6 Tutorials: GUI Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88

Computational Analysis and Engineering Algorithms in MATLAB 93

Conclusion 100

Bibliography 103
List of Figures

1.1 Command Window Mode . . . . . . . . . . . . . . . . . . . . . . . . . . . 5


1.2 Script Mode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6

2.1 The Plot Menu in MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . 46


2.2 Calling Predefined Plotting Functions . . . . . . . . . . . . . . . . . . . . . 47
2.3 Plotting a Sine Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
2.4 Plot Tools Window . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
2.5 Personalized sinus . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
2.6 Customized Sine Plot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
2.7 Plotting Sine and Cosine Together . . . . . . . . . . . . . . . . . . . . . . . 53
2.8 Four Functions in One Figure . . . . . . . . . . . . . . . . . . . . . . . . . 55
2.9 Example of a bar chart . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
2.10 Example of a pie chart . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57
2.11 Example of a 3D Helix . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60
2.12 A paraboloid surface plot . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61
2.13 Example of a 3D contour plot . . . . . . . . . . . . . . . . . . . . . . . . . 62
2.14 Example of a 3D bar chart . . . . . . . . . . . . . . . . . . . . . . . . . . . 63

3.1 The GUIDE Quick Start . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70


3.2 Blank GUI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70
3.3 GUI with axes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71
3.4 Layout editor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71
3.5 Property Inspector . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72
3.6 Creating a Window . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
3.7 A GUI example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76
3.8 Button pressed example . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77
3.9 Update Components example . . . . . . . . . . . . . . . . . . . . . . . . . 79
3.10 App Designer Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83
3.11 Temperature Converter App . . . . . . . . . . . . . . . . . . . . . . . . . . 84
3.12 Temperature Converter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
Introduction

MATLAB is both a programming language and an interactive environment designed


specifically for scientific and engineering computations. Its name stands for MATrix
LABoratory, which reflects its original purpose: the manipulation and analysis of ma-
trices and linear algebraic structures. Over time, MATLAB has evolved into a compre-
hensive and versatile platform that is widely adopted in academia and industry[1]. Today,
it serves as an essential tool in fields such as control systems, signal processing, image
analysis, computational modeling, machine learning, and data visualization. This evolu-
tion from a specialized matrix tool to a full-fledged programming environment illustrates
its adaptability to the growing demands of modern technology and research.

What makes MATLAB unique is its ability to provide an intuitive and user-friendly
environment for solving complex problems that would otherwise require lengthy and in-
tricate coding in low-level languages [2]. Unlike languages such as C or Java, which
demand explicit declarations and extensive syntax, MATLAB emphasizes simplicity and
productivity. Users can perform numerical computations, analyze data, visualize complex
phenomena, and even build interactive applications in just a few lines of code. The inte-
grated development environment (IDE) of MATLAB combines a powerful command-line
interface with a comprehensive editor, a workspace for managing variables, and tools for
debugging and visualization [3]. This makes MATLAB particularly suitable for students
and professionals who need to focus on conceptual understanding and problem-solving
rather than programming intricacies.

The primary objective of this course is to provide students with a strong foundation in
computational thinking and algorithmic problem-solving using MATLAB as a practical
tool. The content is designed to introduce the basic concepts progressively, starting from
the fundamentals of the MATLAB interface, data representation, and basic operations,
before moving to more advanced topics such as control structures, iterative processes, and
vectorized computations. The course also emphasizes data visualization through two- and
three-dimensional graphical representations, highlighting the importance of visual inter-
pretation in engineering and scientific contexts. Finally, the course explores the creation
of graphical user interfaces, allowing students to develop interactive applications that en-

1
hance usability and functionality.

This course is intended for students in the first year of engineering preparatory pro-
grams but is equally relevant for undergraduates in science and technology disciplines
who seek a gentle yet comprehensive introduction to programming. It is also suitable for
beginners in computational methods who aspire to acquire practical skills for solving real-
world problems. By engaging with MATLAB, students will develop not only programming
competence but also the ability to think algorithmically, structure solutions, and analyze
problems logically. These skills are indispensable for success in advanced studies and in
professional careers where computational modeling and data-driven decision-making play
a central role.

The structure of the course has been carefully designed to ensure a gradual learning
curve. It is divided into three major chapters. The first chapter focuses on the fundamen-
tal aspects of MATLAB programming, including variables, constants, input and output
operations, conditional statements, iterative structures, and the essential operations on
vectors and matrices. This chapter lays the groundwork for all subsequent topics by intro-
ducing the core programming principles necessary for scientific computation. The second
chapter addresses the need for visual communication of data and results, covering the
essential techniques for two-dimensional and three-dimensional graphical representation.
Here, students learn not only how to plot curves and surfaces but also how to customize
graphical elements for clarity and professional presentation. The third chapter introduces
students to the design of graphical user interfaces, a topic that combines programming
skills with creativity and user-centric thinking. This chapter enables students to create
interactive applications, moving beyond simple scripts toward real-world tools that pro-
vide intuitive user interaction.

The pedagogical approach adopted in this course emphasizes clarity, accessibility, and
practice. Concepts are explained using straightforward language and reinforced through
practical examples and illustrative exercises. Each section is supported by step-by-step
demonstrations to guide students in applying theoretical concepts to practical scenarios.
The inclusion of tutorials and structured exercises at the end of each chapter encourages
active learning and self-assessment. These exercises are designed to progressively challenge
students, building confidence and competence in problem-solving through programming.

2
Chapter 1

MATLAB Language

1.1 Introduction
MATLAB (short for MATrix LABoratory) is a high-level programming language and
interactive environment widely used for numerical computation, data analysis, and al-
gorithm development. Designed to simplify mathematical operations and visualization,
MATLAB combines programming features with powerful built-in functions, making it an
essential tool for engineers, scientists, and researchers [4]. Its core strength lies in han-
dling matrices and arrays efficiently, which explains its popularity in technical fields such
as signal processing, control systems, image analysis, and machine learning.

This first chapter introduces the fundamental concepts of MATLAB programming,


which serve as the basis for all future applications. We begin by exploring how variables
and constants are created and manipulated, highlighting MATLAB’s dynamic typing and
flexibility. Next, we cover conditional structures that allow decision-making in programs,
followed by iterative structures (loops) that enable repetitive execution of tasks. These
concepts provide the logical framework for solving real-world problems.

The chapter then focuses on vectors and matrices, which are central to MATLAB.
Understanding their creation, indexing, and operations is crucial because they form the
foundation for most numerical computations. Finally, we introduce procedures and func-
tions as a way to structure programs and encourage code reuse. By the end of this chapter,
students will have acquired the skills to write basic MATLAB programs, control program
flow, and manipulate data efficiently—skills that will be expanded in later chapters on
visualization and GUI design.

3
1.2 MATLAB Interface: Two Modes of Use
MATLAB provides a versatile interface that accommodates different programming work-
flows, offering two main modes of interaction: the Command Window Mode and the
Script Mode. Each mode serves a distinct purpose and is best suited to specific tasks
during program development [5].

The Command Window Mode allows users to execute commands interactively,


line by line, in real time. This mode is particularly useful for quick calculations, test-
ing individual instructions, or exploring MATLAB’s built-in functions without creating a
program file. It promotes experimentation, making it ideal for beginners who want to fa-
miliarize themselves with syntax and for advanced users performing rapid prototyping[6].
However, because commands entered in this mode are not saved, it is less suited for long
or reusable programs.

On the other hand, the Script Mode provides an environment for writing and storing
sequences of instructions in files with the .m extension. Scripts allow for better organi-
zation of code, reproducibility of results, and easier debugging. They are essential for
structured program development, especially when working on larger projects or assign-
ments that require multiple steps and parameter adjustments. Using scripts encourages
good programming practices such as modularity and documentation, which are crucial
for collaboration and maintenance in professional environments[7].

By understanding these two modes, students can choose the most effective approach
depending on their objectives—using the Command Window for quick tests and calcula-
tions, while relying on scripts for systematic problem-solving and program development.
In the following subsections, we will explore each mode in detail with practical examples.

1.2.1 Command Window Mode


Users can enter instructions directly into MATLAB’s Command Window, which acts
as an interactive console for executing commands in real time. This feature is particu-
larly useful for quick, one-off computations where writing and saving a complete program
is unnecessary. By typing commands and receiving immediate feedback, users can test
mathematical expressions, verify small sections of code, and experiment with different
operations without creating a script file.

This interactive mode also provides a convenient environment for exploring MATLAB’s
vast library of built-in functions, checking syntax, and performing rapid prototyping of
ideas. For beginners, this approach offers an intuitive and low-barrier entry point to

4
programming, while for experienced users, it serves as an efficient tool for debugging or
validating parts of a larger algorithm before formal implementation[8].

Figure 1.1: Command Window Mode

For example (Figure 1.1 ), typing a = 2 + 3 in the Command Window will instantly
return the result a = 5. This interactive style of programming is particularly useful for
learning and experimentation.

1.2.2 Script Mode


Often referred to as Programming Mode, provides a structured approach to writing
and executing MATLAB code. Unlike the Command Window, which is ideal for quick
tests and small calculations, Script Mode is specifically designed for developing more com-
plex programs that require multiple instructions to be executed in a defined sequence. A
script in MATLAB is essentially a text file with the extension .m that contains a collection
of commands written in a logical order. By using scripts, users can organize their work
efficiently, save it for future reference, and ensure code reusability across different projects
[9]. This approach encourages good programming practices such as documentation, mod-
ularity, and debugging.

Furthermore, scripts allow for automation of repetitive tasks, reducing the risk of
manual errors and improving productivity. For example, when performing large-scale
simulations, plotting multiple figures, or executing iterative calculations, writing a script
becomes indispensable.

5
For instance, in a file named example-script.m, one might write:

Figure 1.2: Script Mode

To run a script, users simply click the Run button in the MATLAB editor or type the
script’s filename (without the extension) in the Command Window, making the execution
process simple and streamlined.

1.3 Variables and Constants


In MATLAB, variables and constants are fundamental concepts that form the basis of
any program. Unlike many traditional programming languages, MATLAB does not make
a strict distinction between variables and constants; instead, both are treated uniformly
in the programming environment. A variable in MATLAB is essentially an identifier or a
symbolic name that refers to a value stored in memory. This value can be of various types,
such as numeric, character strings, logical values, or even more complex structures like
arrays, matrices, and cell arrays. If the value of a variable remains unchanged throughout
the execution of a program, it effectively behaves like a constant, but MATLAB does not
enforce immutability[10]. In other words, constants are not a built-in language feature;
they are simply variables that the programmer chooses not to modify.

One of the most distinctive characteristics of MATLAB is its dynamic typing system.
This means that the programmer is not required to explicitly declare the data type of a

6
variable before using it. In contrast to statically typed languages such as C or Java—where
variables must be declared with specific types like int, float, or char—MATLAB de-
termines the type of a variable automatically at runtime based on the assigned value[11].
For instance, if you write x = 42, MATLAB internally recognizes x as a numeric scalar.
If later in the program you assign a string to the same variable, such as x = ’Hello’,
MATLAB seamlessly updates the type to a character array. This flexibility provides an
intuitive and user-friendly programming experience, especially for beginners, as it allows
developers to focus on problem-solving rather than type management.

Variables in MATLAB follow certain naming rules: they must begin with a letter, can
include digits and underscores, and are case-sensitive, meaning that X and x are treated
as two different identifiers. MATLAB also reserves certain keywords, which cannot be
used as variable names, such as if, end, or while. To check whether a variable exists
or to inspect its details, MATLAB provides commands like who and whos, which display
information about variables currently stored in the workspace, including their size, type,
and memory usage.

Moreover, MATLAB offers several predefined constants that simplify mathematical


computations. For example, pi represents the value of π (approximately 3.1416), inf de-
notes infinity, and NaN (Not a Number) indicates an undefined or unrepresentable numeric
result, such as 0/0. These constants can be used directly in calculations or assigned to
variables for convenience:

r = 2; % Radius of a circle
circumference = 2 * pi * r; % Using predefined constant pi

The dynamic and flexible nature of variables in MATLAB allows for rapid prototyping
and experimentation. However, this flexibility requires careful programming practices to
avoid unintended type changes that may lead to errors in calculations or function calls.
Understanding how MATLAB manages variables and constants is therefore crucial for
writing efficient and error-free programs.

In summary, MATLAB offers a simple and flexible variable handling system, where
types are inferred, declarations are not needed, and constants are simply variables whose
values are not changed.

1.4 Basic Instructions


Before delving into advanced programming concepts, it is essential to understand the ba-
sic instructions in MATLAB, as they constitute the foundation of every program. These

7
basic operations define how data is entered, processed, and displayed, enabling the pro-
grammer to create interactive and dynamic scripts. MATLAB offers a set of commands
and functions that simplify these interactions, making it accessible even for beginners
while maintaining flexibility for advanced applications.

Basic instructions in MATLAB can be grouped into several essential categories. The
first category consists of input/output operations, which allow the user to provide
data to the program and receive feedback in a readable format. This interaction is cru-
cial for creating programs that are not rigid but instead adaptable to user inputs. The
second category involves assignment instructions, which store values in variables for
future computations, forming the backbone of any algorithm. Finally, increment and
decrement operations are used to modify the value of variables dynamically during
execution, often within loops or conditional structures. Mastering these categories is the
first step toward writing efficient, interactive, and well-structured MATLAB programs.

1.4.1 Input/Output Instructions


Input and output operations are among the most fundamental aspects of any program-
ming language because they enable interaction between the user and the computational
environment. In MATLAB, these operations are highly intuitive and versatile, allowing
both textual and numerical data entry and display. They play a critical role in developing
interactive scripts, where the program adapts its behavior based on user-provided values.

Reading Data from the User

MATLAB provides the built-in input() function to capture user input. When this func-
tion is called, it displays a prompt message in the Command Window and pauses the
program until the user enters a value. Once the input is provided, MATLAB assigns it to
the specified variable. This function can capture numeric values, strings, or even arrays
depending on the context.

Example:

X = input(’Enter your name: ’, ’s’); % ’s’ indicates string input

In the example above:

• The message ’Enter your name:’ appears in the Command Window.

• The program waits until the user types a response and presses Enter.

8
• The second argument ’s’ ensures the input is read as a string rather than as a
numeric value.

Without the ’s’ argument, MATLAB expects numeric input by default. If the user
enters a non-numeric value in that case, an error will occur.

Displaying Data to the User

Once data is processed, it is often necessary to display results or status messages to the
user. MATLAB offers multiple ways to accomplish this, including the disp() function,
the display() function, and the more advanced fprintf() function for formatted output.

Example using disp():

name = input(’Enter your name: ’, ’s’);


disp([’Hello ’, name]);

This program combines static text with the user’s input and displays the greeting. The
disp() function is ideal for quick outputs, as it automatically handles line breaks and
requires minimal formatting.

Example using fprintf():

age = input(’Enter your age: ’);


fprintf(’Hello, you are %d years old.\n’, age);

In this example:

• The %d placeholder indicates that an integer value will be printed.

• The \n adds a line break for readability.

• fprintf() allows for precise control over formatting, making it suitable for profes-
sional reports or structured output.

Practical Tips

• Always provide clear and concise prompt messages to guide the user.

• Validate inputs when necessary to avoid unexpected errors (e.g., ensure numeric
input for mathematical operations).

• Use fprintf() instead of disp() when formatting or alignment is important, such


as displaying tabular data.

9
Why Input/Output Operations Matter

Interactive programs are easier to adapt to real-world scenarios where data changes fre-
quently. For example, a static program that calculates the area of a circle using a hard-
coded radius is of limited use. By using input/output instructions, the same program
can request the radius from the user and display the result in a user-friendly format, thus
becoming reusable for any value.

Example: Area Calculation Program

radius = input(’Enter the radius of the circle: ’);


area = pi * radius^2;
fprintf(’The area of the circle is %.2f\n’, area);

This program:
• Accepts dynamic input from the user.

• Performs the calculation using MATLAB’s built-in constant pi.

• Displays the result with two decimal places using fprintf().


Mastering input and output operations is a cornerstone of programming in MATLAB.
They transform static scripts into dynamic tools capable of solving diverse problems
interactively. Whether you are developing simple scripts or complex applications, un-
derstanding how to read from and write to the user effectively is essential for creating
practical, user-oriented solutions.

1.4.2 Assignment Instructions


Assignment is one of the most fundamental concepts in any programming language, and
MATLAB is no exception. The assignment operation allows a programmer to store a
value in a variable so that it can be used later in computations or as input to other oper-
ations. This simple concept forms the backbone of programming because every algorithm
relies on storing and manipulating data through variables.

In MATLAB, the assignment operator is represented by the equal sign =. The syntax
is straightforward: the variable name is placed on the left-hand side of the operator,
while the value or expression to be assigned appears on the right-hand side. The general
structure is:

variable = expression;

This means that the expression on the right is evaluated first, and its result is then stored
in the variable on the left.

10
Basic Example of Assignment

x = 10;
y = 5;
z = x + y;

In this example:
• The variable x is assigned the value 10.

• The variable y is assigned the value 5.

• The variable z stores the sum of x and y, which is 15.


Unlike many statically typed languages such as C or Java, MATLAB does not require
the programmer to declare the type of a variable before use[12]. Instead, it is a dynamically
typed language, meaning the type of the variable is determined at runtime based on the
assigned value. This feature allows for rapid development and greater flexibility, but it
also requires programmers to be attentive to avoid unexpected type changes.

Case Sensitivity in MATLAB

One important aspect to note is that MATLAB is case-sensitive. This means that variable
names such as X and x are treated as two entirely different variables. For example:

x = 10;
X = 20;
disp(x); % Outputs 10
disp(X); % Outputs 20

Failing to account for case sensitivity can lead to logical errors that are sometimes difficult
to detect. Therefore, consistent naming conventions (such as using lowercase for variables
and uppercase for constants) are highly recommended.

Updating Variable Values

Assignments in MATLAB are not static. A variable can be reassigned at any time during
program execution, making it possible to update values dynamically as computations
progress. For example:

a = 5; % Initial assignment
a = a + 10; % Reassign after increment
disp(a); % Displays 15

This flexibility is particularly useful in loops or iterative algorithms where the value
of a variable changes repeatedly.

11
Assignment of Expressions and Function Results

The right-hand side of an assignment statement in MATLAB can be:

1. A constant or literal value:


piValue = 3.1416;

2. A mathematical expression:
result = (5 + 3) * 2; % Evaluates to 16

3. A call to a function:
maxVal = max([4 7 1 9]); % Returns the largest element: 9

Assignments can also involve built-in constants such as pi, inf, or NaN, allowing for
convenient computations without redefining common mathematical values.

Common Pitfalls and Best Practices

• Uninitialized variables: Using a variable before assigning it a value results in an


error.

• Accidental type changes: Since MATLAB is dynamically typed, reassigning a


variable to a different type can lead to unexpected behavior.

• Overwriting important variables: Avoid using variable names that coincide with
MATLAB functions (e.g., naming a variable sum or mean) to prevent shadowing.

• Readable code: Choose descriptive variable names to make your code self-explanatory.

Practical Example: Temperature Conversion

The following example demonstrates assignment combined with basic arithmetic opera-
tions:
celsius = 25; % Temperature in Celsius
fahrenheit = (celsius * 9/5) + 32;
fprintf(’Temperature: ’, fahrenheit);

Here:

• celsius stores the input temperature in degrees Celsius.

12
• fahrenheit is assigned the computed value using the conversion formula.

Assignments like these illustrate how variables serve as building blocks for larger pro-
grams, enabling flexible and readable code design.

1.4.3 Increment and Decrement Operations


In many programming scenarios, especially when working with loops, counters, or itera-
tive algorithms, it becomes necessary to modify the value of a variable repeatedly. Two
common operations in this context are increment (increasing the value) and decre-
ment (decreasing the value). These operations are critical in implementing counting
mechanisms, numerical algorithms, and control structures such as for and while loops.

Definition:

• Increment: The process of increasing a variable’s value by a fixed amount (often


by 1).

• Decrement: The process of reducing a variable’s value by a fixed amount (often


by 1).

Syntax in MATLAB

MATLAB provides a simple and explicit way to perform these operations using the as-
signment operator combined with an arithmetic expression. The general structure is:

variable = variable + value; % Increment


variable = variable - value; % Decrement

Example: Basic Increment and Decrement

i = 0; % Initialize variable
i = i + 1; % Increment by 1
i = i - 1; % Decrement by 1

Unlike some programming languages such as C, C++, or Java, MATLAB does not support
shorthand operators like ++ or –. Therefore, you always need to use the full expression
(e.g., i = i + 1) for incrementing and i = i - 1 for decrementing a variable.

13
Why Does MATLAB Avoid ++ and –?

The absence of ++ and – in MATLAB is intentional for clarity and to reduce ambiguity.
While these shorthand operators may seem convenient, they often introduce confusion
regarding whether the operation is performed before or after the variable is used (prefix
vs postfix). MATLAB aims to maintain code readability and simplicity, especially for
beginners and non-programmers.

Custom Increment/Decrement Values

While increments of 1 are the most common, MATLAB allows you to increase or decrease
a variable by any numeric value:
x = 0;
x = x + 2; % Increment by 2
x = x - 3; % Decrement by 3

This flexibility is useful in scenarios like:

• Generating even or odd sequences.

• Adjusting simulation parameters in fixed steps.

• Creating geometric or arithmetic progressions.

Best Practices and Tips

• Always ensure that increment or decrement operations bring the loop closer to its
exit condition; otherwise, you risk creating an infinite loop.

• For readability, keep increments/decrements simple. Avoid combining them with


complex expressions in the same statement.

• Use descriptive variable names to make code self-documenting (e.g., index, counter,
or step instead of i when appropriate).

Key Takeaway: Increment and decrement operations are simple but essential compo-
nents of MATLAB programming. Their correct use ensures efficient iteration, controlled
loops, and logical program flow.

14
1.4.4 Practical exercises
Exercise 1: Write a MATLAB script that asks the user for their age and then displays
a message: “You are [age] years old.”

% Exercise 1 Solution %
age = input(’Enter your age: ’);
disp([’You are ’, num2str(age), ’ years old.’]);

num2str(age) converts the numeric value to a string so it can be concatenated with text.

Exercise 2: Create a program that initializes a variable with value 10 and then
increments it three times using assignment operations. Display the result after each
increment.

% Exercise 2 Solution %
x = 10;
x = x + 1;
disp(x);
x = x + 1;
disp(x);
x = x + 1;
disp(x);

Exercise 3: Modify the previous program to include a decrement step at the end and
display the final value.

% Exercise 3 Solution
x = 10;
x = x + 1;
disp(x);
x = x + 1;
disp(x);
x = x + 1;
disp(x);
% Decrement step
x = x - 1;
disp([’After decrement: x = ’, num2str(x)]);

15
1.5 Conditional Structures in MATLAB
Conditional structures are fundamental in programming because they enable the execution
of different instructions based on specific conditions. In real-world scenarios, decision-
making is essential: for example, determining whether a user input is valid, whether
a temperature exceeds a threshold, or whether a financial transaction should proceed.
MATLAB provides a clear and intuitive syntax for implementing such decision-making
through conditional statements.

At its core, a conditional structure evaluates a logical expression (true or false) and
executes a block of code depending on the outcome. This mechanism allows programs
to adapt their behavior dynamically instead of following a fixed sequence of instructions.
The most common form of conditional logic in MATLAB is the if-else statement.

Why Are Conditional Structures Important? Conditional statements make pro-


grams intelligent. They allow the execution flow to diverge based on different situations,
creating flexibility and robustness in the program. Without conditional structures, every
program would simply execute instructions sequentially, which is impractical for handling
variable inputs and real-world problems.

1.5.1 General Form


The general syntax of a simple conditional structure in MATLAB is:

if condition
Instruction1
else
Instruction2
end

This means:

• If the condition evaluates to true, MATLAB executes Instruction1.

• Otherwise, MATLAB executes Instruction2.

Every if block must end with the keyword end. This clear termination avoids ambi-
guity and improves code readability.

16
Example 1: Basic if-else Decision

X = input(’Enter a number: ’);


if X > 0
disp(’The number is positive’);
else
disp(’The number is negative or zero’);
end

Explanation:

• The program asks the user to input a number and stores it in variable X.

• The condition X > 0 is checked:

– If true, MATLAB displays: "The number is positive".


– Otherwise, it displays: "The number is negative or zero".

Key Points:

• MATLAB does not require parentheses around the condition, but they can be used
for clarity.

• Indentation is recommended for readability, even though MATLAB does not enforce
it.

1.5.2 Alternative Conditional Structures


MATLAB provides additional forms of conditional statements for more complex decisions:

1. if-elseif-else Chain This structure is used when multiple conditions need to be tested
sequentially.

score = input(’Enter your score: ’);


if score >= 90
disp(’Grade: A’);
elseif score >= 80
disp(’Grade: B’);
elseif score >= 70
disp(’Grade: C’);
else
disp(’Grade: F’);
end

17
How It Works:

• MATLAB evaluates each condition in order.

• Once a condition evaluates to true, the corresponding block executes, and the rest
are ignored.

• If no condition is true, the else block runs.

2. Nested if Statements An if statement inside another if is called a nested if. This


is useful for multi-level decision-making:

x = input(’Enter a number: ’);


if x > 0
if mod(x,2)==0
disp(’Positive and Even’);
else
disp(’Positive and Odd’);
end
else
disp(’Negative or Zero’);
end

3. Multiple Conditions with Logical Operators When a decision depends on two


or more conditions simultaneously, MATLAB uses logical operators:

• && (AND) → True if both conditions are true.

• || (OR) → True if at least one condition is true.

age = input(’Enter your age: ’);


if (age >= 18) && (age <= 30)
disp(’Age between 18 and 30’);
end

temp = input(’Enter temperature: ’);


if (temp < 0) || (temp > 40)
disp(’Extreme temperature’);
end

Important Tip: Always use parentheses for clarity when combining conditions.

18
1.5.3 Comparison and Logical Operators in MATLAB
Comparison Operators:

• == Equal to

• = Not equal to

• > Greater than

• < Less than

• >= Greater than or equal to

• <= Less than or equal to

Logical Operators:

• && Logical AND

• || Logical OR

• ˜ Logical NOT

1.5.4 Real-World Applications of Conditional Structures


Conditional structures are widely used in real-world MATLAB programs:

• **Data Validation:** Checking if user input is within a valid range.

• **Control Systems:** Switching modes based on sensor feedback.

• **Scientific Simulations:** Applying different models based on conditions (e.g., tem-


perature thresholds).

• **Finance:** Approving or rejecting transactions based on rules.

19
1.5.5 Practical Exercises
Exercise 1: Positive, Negative, or Zero
num = input(’Enter an integer: ’);
if num > 0
disp(’The number is positive’);
elseif num < 0
disp(’The number is negative’);
else
disp(’The number is zero’);
end

Exercise 2: Grade Evaluation


grade = input(’Enter the student’’s grade: ’);
if grade > 16
disp(’Excellent’);
elseif grade >= 12 && grade <= 16
disp(’Good’);
else
disp(’Needs Improvement’);
end

Additional Challenge: Password Verification


password = input(’Enter password: ’,’s’);
if strcmp(password,’MATLAB123’)
disp(’Access Granted’);
else
disp(’Access Denied’);
end

1.6 Iterative Structures in MATLAB


Iterative structures, commonly known as loops, are essential control mechanisms in pro-
gramming that allow the execution of a set of instructions repeatedly based on a specified
condition. Instead of manually repeating code lines, loops automate repetitive tasks,
making programs shorter, clearer, and more efficient.
In MATLAB, iterative structures play a crucial role in numerous computational tasks.
They are widely used in:

• Numerical Computations: Performing repeated calculations such as summing


large sequences or approximating integrals.

20
• Data Processing: Iterating through arrays, vectors, and matrices for operations
such as filtering or transformations.

• Simulations: Running models iteratively to simulate time-dependent phenomena.

• Automation: Executing a block of code multiple times without rewriting it.

Without loops, any operation requiring repetition would require multiple redundant
lines of code, which is error-prone and difficult to maintain. Loops provide a systematic
way to handle such repetitive tasks with flexibility and control.

MATLAB provides two primary loop structures:

1. while loop — Executes a block of code repeatedly as long as a condition remains


true. This is ideal when the number of iterations is unknown beforehand.

2. for loop — Executes a block of code a fixed number of times, making it suitable
when the number of iterations is known in advance.

Both loops serve unique purposes and are fundamental tools in developing MATLAB
programs that are dynamic and efficient.

1.6.1 While Loop


The while loop is particularly useful when the number of iterations cannot be prede-
termined, and the process should continue until a certain condition becomes false. The
syntax of a while loop in MATLAB is:

while condition
% Statements to execute
end

Explanation of Syntax:

• condition: A logical expression evaluated before each iteration.

• If condition is true, the block inside the loop executes.

• If false initially, the loop does not execute even once.

Key Characteristics of a While Loop:

• It is used when the termination point is determined by a logical condition rather


than a fixed number of repetitions.

• The condition is checked before each iteration, making it a pre-test loop.

21
• Failing to update the variables involved in the condition may lead to an infinite
loop.

Example 1: Print a Word Multiple Times

i = 1;
while i < 5
disp(’Hello’);
i = i + 1; % Increment counter
end

Explanation: The loop continues as long as i is less than 5. After each iteration, i is
incremented by 1. When i becomes 5, the condition fails, and the loop ends.

Example 2: Sum of Numbers Until Threshold

sumValue = 0;
i = 1;
while sumValue <= 50
sumValue = sumValue + i;
i = i + 1;
end
disp([’Sum exceeded 50: ’, num2str(sumValue)]);

Explanation: This program keeps adding consecutive integers starting from 1 until the
sum exceeds 50. The final sum and the last number added are displayed.

Infinite While Loop: If the condition never becomes false, the loop runs indefinitely:

while true
disp(’This will run forever!’);
end

To stop such a loop, press Ctrl + C in the MATLAB Command Window.

22
1.6.2 For Loop
The for loop is used when the number of iterations is known in advance. It is commonly
applied in operations involving sequences, such as traversing an array or generating tables.
The syntax of a for loop is:

for index = start:step:stop


% Statements to execute
end

Explanation of Components:
• index: Loop control variable that takes values from start to stop.

• start:step:stop: Defines the range and increment:

– start: Initial value.


– step: Increment between values (default = 1 if omitted).
– stop: Final value (loop stops when index exceeds this).

Example 1: Display Numbers from 1 to 5

for i = 1:5
disp([’Value: ’, num2str(i)]);
end

Example 2: Multiplication Table of 7

for i = 1:10
result = 7 * i;
disp([’7 x ’, num2str(i), ’ = ’, num2str(result)]);
end

Example 3: Display Even Numbers from 2 to 20

for i = 2:2:20
disp(i);
end

Key Observations:
• MATLAB handles the loop counter automatically; no manual incrementing is re-
quired.

• A negative step value allows counting backward.

23
1.6.3 While vs For Loop
Both while and for loops achieve repetition, but they differ in their use cases:

• Use while when the termination condition depends on runtime computations or


user input.

• Use for when the number of iterations is known in advance or can be determined
before the loop starts.

Comparison Summary:

• while: Pre-test loop, flexible but requires manual control of termination.

• for: Count-controlled loop, simpler for sequences and ranges.

1.6.4 Real-World Applications of Loops in MATLAB


• Processing large datasets row by row.

• Generating simulation data for engineering models.

• Creating automated reports.

• Iteratively adjusting algorithm parameters until convergence.

1.6.5 Practical Exercises


Exercise 1: Sum Consecutive Integers Until Sum > 100

sumValue = 0;
i = 1;
while sumValue <= 100
sumValue = sumValue + i;
i = i + 1;
end
disp([’Final Sum: ’, num2str(sumValue)]);
disp([’Last number added: ’, num2str(i-1)]);

24
Exercise 2: Sum of First 20 Even Numbers

sumEven = 0;
for i = 2:2:40
sumEven = sumEven + i;
end
disp([’Sum of first 20 even numbers: ’, num2str(sumEven)]);

Exercise 3: Factorial Calculation Using Loops

n = input(’Enter a number: ’);


fact = 1;
for i = 1:n
fact = fact * i;
end
disp([’Factorial of ’, num2str(n), ’ is ’, num2str(fact)]);

1.7 Complex Structures: Vectors & Matrices


Vectors and matrices are the core data structures in MATLAB. In fact, the name MAT-
LAB itself originates from “MATrix LABoratory”, emphasizing the importance of matrix-
based operations. Unlike many programming languages that distinguish between arrays,
lists, and matrices, MATLAB treats almost every variable as an array. This design makes
MATLAB extremely powerful for numerical computations, scientific research, and engi-
neering applications[13].

In many real-world applications—such as physics simulations, control systems, signal


processing, machine learning, and image processing—data is often represented in the form
of vectors and matrices. Hence, understanding how to create, manipulate, and operate
on these structures is crucial for effective MATLAB programming.

1.7.1 Definition and Types of Vectors


A vector is a one-dimensional array of numbers. In MATLAB, vectors are fundamental
because they serve as the building blocks for more complex data structures, such as
matrices and higher-dimensional arrays. There are two main types of vectors in MATLAB:

25
Row Vector: A row vector is a horizontal sequence of elements enclosed in square
brackets, separated by spaces or commas.

rowVector = [1 2 3 4 5];
% or using commas:
rowVector = [1, 2, 3, 4, 5];

Column Vector: A column vector is a vertical sequence of elements separated by semi-


colons.

colVector = [1; 2; 3; 4; 5];

Real-world application: In physics, a velocity vector can be represented as [vx vy


vz], where each component corresponds to a direction in 3D space. Similarly, in finance,
a portfolio can be represented as a vector of asset weights.

1.7.2 Matrix Definition


A matrix is a two-dimensional array of numbers organized in rows and columns. In
MATLAB, creating a matrix is simple:

A = [1 2 3; 4 5 6; 7 8 9];

Here:

• Elements in the same row are separated by spaces or commas.

• Rows are separated by semicolons.

Example: The above command creates a 3 × 3 matrix.

1.7.3 Accessing Elements


You can access elements of a vector or matrix using indexing:

• Vectors: Indexing starts from 1 (not 0, unlike in languages such as C or Python).

x = [10 20 30 40];
element = x(3); % Access the 3rd element

26
• Matrices: Use A(row, column) to access an element.

A = [1 2 3; 4 5 6; 7 8 9];
value = A(2,3); % Row 2, Column 3

Tip: You can access an entire row or column using the colon operator:

row2 = A(2,:); % Entire 2nd row


col3 = A(:,3); % Entire 3rd column

1.7.4 Creating Vectors with Operators


MATLAB provides convenient ways to create vectors without manually listing all ele-
ments:

v = 1:5; % [1 2 3 4 5]
v = 0:2:10; % [0 2 4 6 8 10] (start:step:stop)

This feature is extremely useful for generating sequences for plotting or simulations.

1.7.5 Basic Operations on Vectors and Matrices


MATLAB supports a wide range of operations. Operations are either:

• Element-wise (Hadamard): Performed element by element.

• Matrix operations: Follow linear algebra rules.

Examples:

• Addition/Subtraction:

a = [1 2 3];
b = [4 5 6];
c = a + b; % Result: [5 7 9]

• Scalar Multiplication:

d = 3 * a; % Result: [3 6 9]

27
• Matrix Multiplication:

A = [1 2; 3 4];
B = [5; 6];
C = A * B; % Result: [17; 39]

1.7.6 Common Functions for Vectors and Matrices


• length(v): Returns the number of elements in a vector.

• size(A): Returns the dimensions of a matrix.

• sum(v): Calculates the sum of vector elements.

• mean(v): Calculates the mean of vector elements.

• max(v), min(v): Find maximum and minimum values.

• diag(A): Extracts the diagonal elements of a matrix.

1.7.7 Matrix Transpose and Inverse


• Transpose:

A = [1 2 3; 4 5 6];
A_T = A’; % Transpose of A

• Inverse (for square matrices only):

B = [1 2; 3 4];
B_inv = inv(B);

1.7.8 Element-wise Operations


To perform element-by-element multiplication or division, use the dot operator:

x = [1 2 3];
y = [4 5 6];
z = x .* y; % Result: [4 10 18]

28
1.7.9 Advanced Operations and Real-World Applications
1. Computing Norms:

v = [3 4];
normValue = norm(v); % Euclidean norm

2. Solving Linear Systems:

A = [2 1; 1 -1];
b = [3; 1];
x = A \ b; % Solves Ax = b

3. Data Analysis: Vectors and matrices are essential for storing datasets. For example,
a 100x4 matrix can represent 100 observations of 4 variables in statistical analysis.

1.7.10 Practical Exercises


Exercise 1: Create a row vector containing numbers from 5 to 25 with a step of 5.
Display the result.

v = 5:5:25;
disp(v);

Exercise 2: Create a 3 × 3 matrix with values from 1 to 9. Compute its transpose and
display both.

A = [1 2 3; 4 5 6; 7 8 9];
disp(’Matrix A:’);
disp(A);
disp(’Transpose of A:’);
disp(A’);

Exercise 3: Compute the sum and mean of the following vector: x = [10 20 30 40
50];

x = [10 20 30 40 50];
s = sum(x);
m = mean(x);
disp([’Sum: ’, num2str(s)]);
disp([’Mean: ’, num2str(m)]);

29
Exercise 4: Perform element-wise multiplication of two vectors: a = [2 4 6]; b = [1
3 5];

a = [2 4 6];
b = [1 3 5];
c = a .* b;
disp(c);

Exercise 5 (Advanced): Solve the system of equations: 2x + y = 5 x − y = 1

A = [2 1; 1 -1];
b = [5; 1];
solution = A \ b;
disp(’Solution:’);
disp(solution);

1.8 Procedures and Functions


In programming, modularity and reusability are essential principles for writing effi-
cient, organized, and maintainable code. Instead of writing large monolithic programs,
it is recommended to divide tasks into smaller, reusable units. MATLAB supports these
principles through procedures (scripts) and functions. Additionally, MATLAB pro-
vides an extensive library of predefined (built-in) functions that simplify common
operations.

1.8.1 Procedures in MATLAB (Scripts)


A procedure in MATLAB is essentially a script—a text file containing a series of MAT-
LAB commands saved with the extension .m. When executed, MATLAB runs these
commands sequentially from the first line to the last. Scripts are particularly useful for
automating repetitive tasks, performing computations, and quickly testing algorithms.

Characteristics of Scripts

• They do not accept input arguments or return outputs by default.

• Scripts share the same workspace as the Command Window (called the base workspace).

• Ideal for simple computations, simulations, and quick experiments.

30
Example: A Simple Script

% File: myScript.m
x = 5;
y = 10;
sumVal = x + y;
disp([’Sum = ’, num2str(sumVal)]);

To execute the script, type:

myScript

1.8.2 Functions in MATLAB


While scripts are useful, they lack flexibility because they cannot accept inputs or return
outputs. Functions, on the other hand, allow modular programming. They:

• Accept input arguments.

• Return output values.

• Have their own local workspace, isolated from the base workspace.

General Syntax of a Function

function [output1, output2, ...] = functionName(input1, input2, ...)


% Function body
end

Example: A Function to Compute Square

% File: squareNumber.m
function result = squareNumber(x)
result = x^2;
end

Call the function:

y = squareNumber(6); % y = 36

31
Functions with Multiple Outputs

MATLAB functions can return several outputs:

% File: basicStats.m
function [sumVal, meanVal] = basicStats(v)
sumVal = sum(v);
meanVal = mean(v);
end

Usage:

[a, b] = basicStats([1 2 3 4 5]);


disp([’Sum = ’, num2str(a), ’, Mean = ’, num2str(b)]);

Anonymous Functions

Anonymous functions are one-line functions that do not require a separate file:

f = @(x) x^2 + 3*x + 5;


res = f(4); % res = 33

Local vs Global Variables

• Variables inside a function are local by default.

• To share variables between functions, declare them as global:

global X;
X = 100;

32
1.8.3 Predefined Functions in MATLAB
MATLAB includes many predefined functions to perform common tasks. These built-in
functions save time and ensure optimized performance.

Examples of Predefined Functions

Mathematical Functions:

sqrt(16) % Square root -> 4


abs(-10) % Absolute value -> 10
power(2, 3) % 2^3 -> 8
round(3.75) % -> 4

Statistical Functions:

mean([1 2 3 4]) % -> 2.5


max([3 7 2]) % -> 7
min([3 7 2]) % -> 2
sum([1 2 3]) % -> 6
std([12 15 20]) % Standard deviation

Trigonometric Functions:

sin(pi/2) % -> 1
cos(0) % -> 1
tan(pi/4) % -> 1

String Functions:

str = ’Hello’;
len = length(str); % -> 5
upper(str) % -> ’HELLO’
lower(str) % -> ’hello’

33
1.8.4 Comparison: Scripts vs Functions

Scripts Functions
Do not accept inputs or re- Accept inputs and return
turn outputs by default outputs
Share base workspace Have their own local
workspace
Good for simple tasks and Good for modular, reusable
automation code

Table 1.1: Comparison between Scripts and Functions in MATLAB

1.8.5 Practical Exercises


Exercise 1: Script for Sum

• Ask the user for two numbers

• Compute their sum

• Display the result

Solution:

% computeSum.m
a = input(’Enter first number: ’);
b = input(’Enter second number: ’);
sumVal = a + b;
disp([’Sum = ’, num2str(sumVal)]);

Exercise 2: Circle Calculations Create a function circleCalc that returns the


area and circumference of a circle given its radius.
Solution:

% circleCalc.m
function [area, circumference] = circleCalc(r)
area = pi * r^2;
circumference = 2 * pi * r;
end

34
Exercise 3: Predefined Functions Compute the standard deviation and maximum
value of the vector v = [12 15 20 22 18].
Solution:

v = [12 15 20 22 18];
stdVal = std(v);
maxVal = max(v);
disp([’Std Dev = ’, num2str(stdVal), ’, Max = ’, num2str(maxVal)]);


Exercise 4: Advanced Function Write a function quadraticSolver(a,b,c) that
returns the roots of the quadratic equation ax2 + bx + c = 0 and the discriminant.
Solution:

% quadraticSolver.m
function [root1, root2, disc] = quadraticSolver(a,b,c)
disc = b^2 - 4*a*c;
if disc >= 0
root1 = (-b + sqrt(disc)) / (2*a);
root2 = (-b - sqrt(disc)) / (2*a);
else
root1 = NaN;
root2 = NaN;
end
end

35

You might also like