Chapter 1 Matlab
Chapter 1 Matlab
MATLAB Foundations
A Computational Environment for Future Engineers
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
Conclusion 100
Bibliography 103
List of Figures
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.
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].
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.
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].
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.
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:
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.
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.
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.
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.
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:
• 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.
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.
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.
In this example:
• 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).
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.
This program:
• Accepts dynamic input from the user.
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.
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.
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
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.
• 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.
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:
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.
Definition:
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:
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.
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
• Always ensure that increment or decrement operations bring the loop closer to its
exit condition; otherwise, you risk creating an infinite loop.
• 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.
if condition
Instruction1
else
Instruction2
end
This means:
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
Explanation:
• The program asks the user to input a number and stores it in variable X.
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. if-elseif-else Chain This structure is used when multiple conditions need to be tested
sequentially.
17
How It Works:
• Once a condition evaluates to true, the corresponding block executes, and the rest
are ignored.
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
Logical Operators:
• || Logical OR
• ˜ Logical NOT
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
20
• Data Processing: Iterating through arrays, vectors, and matrices for operations
such as filtering or transformations.
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.
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.
while condition
% Statements to execute
end
Explanation of Syntax:
21
• Failing to update the variables involved in the condition may lead to an infinite
loop.
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.
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
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:
Explanation of Components:
• index: Loop control variable that takes values from start to stop.
for i = 1:5
disp([’Value: ’, num2str(i)]);
end
for i = 1:10
result = 7 * i;
disp([’7 x ’, num2str(i), ’ = ’, num2str(result)]);
end
for i = 2:2:20
disp(i);
end
Key Observations:
• MATLAB handles the loop counter automatically; no manual incrementing is re-
quired.
23
1.6.3 While vs For Loop
Both while and for loops achieve repetition, but they differ in their use cases:
• Use for when the number of iterations is known in advance or can be determined
before the loop starts.
Comparison Summary:
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)]);
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];
A = [1 2 3; 4 5 6; 7 8 9];
Here:
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:
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.
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]
A = [1 2 3; 4 5 6];
A_T = A’; % Transpose of A
B = [1 2; 3 4];
B_inv = inv(B);
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
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.
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);
A = [2 1; 1 -1];
b = [5; 1];
solution = A \ b;
disp(’Solution:’);
disp(solution);
Characteristics of Scripts
• Scripts share the same workspace as the Command Window (called the base workspace).
30
Example: A Simple Script
% File: myScript.m
x = 5;
y = 10;
sumVal = x + y;
disp([’Sum = ’, num2str(sumVal)]);
myScript
• Have their own local workspace, isolated from the base workspace.
% File: squareNumber.m
function result = squareNumber(x)
result = x^2;
end
y = squareNumber(6); % y = 36
31
Functions with Multiple Outputs
% File: basicStats.m
function [sumVal, meanVal] = basicStats(v)
sumVal = sum(v);
meanVal = mean(v);
end
Usage:
Anonymous Functions
Anonymous functions are one-line functions that do not require a separate file:
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.
Mathematical Functions:
Statistical Functions:
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
Solution:
% computeSum.m
a = input(’Enter first number: ’);
b = input(’Enter second number: ’);
sumVal = a + b;
disp([’Sum = ’, num2str(sumVal)]);
% 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