0% found this document useful (0 votes)
30 views46 pages

Introduction to MATLAB Programming Basics

pdfffff

Uploaded by

Aqua Zone
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)
30 views46 pages

Introduction to MATLAB Programming Basics

pdfffff

Uploaded by

Aqua Zone
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

Welcomes

12 programmes Ranked 801-1000 in Ranked 801-850 in Ranked 52nd in


A Grade accredited Rankings 2024 World Rankings 2025 Rankings 2023*
1
* University Category
Module 1

Getting started with MATLAB


Introduction
• The name MATLAB stands for MATrix LABoratory. MATLAB was written originally
to provide easy access to matrix software developed by the LINPACK (linear
system package) and EISPACK (Eigen system package) projects.

• In comparison to general-purpose programming languages, MATLAB makes it far


easier to add one matrix to another, to subtract them, and to multiply them, and
it allows us to perform many other operations on them as well. This focus on
matrices is apparent from the name, “MATLAB”. Its matrix operations are to a
large extent what makes MATLAB such a good language for programming
solutions to problems in engineering and science, each of which often involves
matrices.
• MATLAB is a mathematical and graphical software package with numerical,
graphical, and programming capabilities.
• It includes an integrated development environment, as well as both procedural
and object-oriented programming constructs.
• It has built-in functions to perform many operations, and there are Toolboxes that
can be added to augment these functions (e.g., for signal processing).
Getting started with MATLAB interface and
workspace
• When the MATLAB software is started, a window opens in which the main part is
the Command Window (see Fig. 1).
• In the Command Window, you should see: >> The symbol >> in the Command
Window indicates that MATLAB is ready to obey your every command.
• In computer-science parlance, this symbol is called a “prompt”. A prompt is a
symbol, or symbols, used by a program (MATLAB is a program) while it is running
to request an action from the user−such as typing a command.
• Thus, MATLAB is using the double “greater-than sign” >> as its command prompt.
Fig 1: The graphical interface to the MATLAB workspace
• The following commands can serve as an introduction to MATLAB and allow you
to get help:
• demo will bring up MATLAB Examples in the Help Browser, which has examples of
some of the features of MATLAB
• help will explain any function; help help will explain how help works
• lookfor searches through the help for a specific word or phrase (Note: this can
take a long time)
• doc will bring up a documentation page in the Help Browser
• To exit from MATLAB, either type quit or exit at the prompt, or click on MATLAB,
then Quit MATLAB from the menu.
Resources
• Fitzpatrick, J. M., & Lédeczi, Á. (2015). Computer Programming with MATLAB.
Cengage Learning. Attaway, S. (2019).

• MATLAB: A Practical Introduction to Programming and Problem Solving (5th ed.).


Butterworth-Heinemann.
Additional Online Resources
• Introducing MATLAB
[Link]
• Getting Started with MATLAB
[Link]
[Link]
• Introducing MATLAB Mobile
[Link]
Module 1

Introduction to basics of computer


programming and terminologies
Interpreting
• In the language of computer science, executing a command by a computing
environment, such as MATLAB, is termed interpreting the command. MATLAB
interprets (i.e., executes) the command typed in the command window as soon
as you have completed the command and have hit the Enter key.
Syntax
• The form of MATLAB's commands must obey certain rules. If they do not, then
MATLAB cannot interpret them, and it gives an error message in bright red: For
example, to create a variable x whose value is 1. At the command prompt, the
following command is typed
• 1=x
• A message appears in red as soon as press ‘Enter’. The message is MATLAB trying
to tell us what is wrong. In this case, the user probably does not realize that the
equal sign does not mean "is equal to". This is an assignment statement, which
means instead, "Assign the value of the expression on the right side of the equal
sign to the variable that is on the left side.“

• Constants, such as 1, 2, or –18.9, cannot be assigned values. Thus, constants


cannot appear on the left side of an equal sign.

• The form of a statement is its syntax. Any violation of the form is called a “syntax
error”.
Variable
• Each time you assign a value to a new variable, MATLAB puts the name of that
variable into a table and sets aside enough room to hold its value.

• Variables are used to store data that can be used and manipulated throughout a
program.
Creating Variables:

The command creates 3 variables a,b and c and they can be views in the workspace.
The workspace
• As we use more variables, we use more memory space. MATLAB, calls a collection
of defined variables a workspace. If at any time, you wish to see the variables that
you have brought into existence by assigning values to them, you can either look
at the Workspace
Program and Algorithm
• A program is any sequence of symbols that describes an algorithm.

• An algorithm is a step-by-step procedure for solving a problem.

• A computer program is a program that describes an algorithm in a language that


can be executed on a computer.
Source code and executable code:
• The text that you enter into an M-file by using the edit window is a sequence of
symbols that describes an algorithm in a language that can be executed on a
computer, and therefore, it is a computer program, but it is sometimes also called
code or source code or source.

• Before the computer runs the code that a programmer writes, it typically must
translate it into an equivalent program called executable code that is written in
language that, unlike source code, can be executed directly by the computer.
Vectors
• A vector in mathematics and in computer science is simply an ordered list of
numbers, and each number is called an element of the vector.
• A vector can be created in MATLAB, as shown above, by using a pair of brackets ([
]) to enclose a list of numbers separated by spaces, commas, or both.
• The commands below set x and y equal respectively to two 8-element vectors.
• >> x = [1 2 3 4 5 6 7 8];
• >> y = [1 2 3 5 8 13 21 34];
Vectors
Index
• “index”, in MATLAB terminology means a positive integer that enumerates the
elements of a vector.
Matrices And Arrays
A matrix is two-dimensional with rows and columns and rectangular arrangement
of numbers, such as this 2-by-3, matrix, which has 2 rows and 3 columns:
• A matrix is a special case of an array.
• An array can be multi-dimensional (1D, 2D, 3D, or higher).
• A scalar, which is a single number in mathematics, is treated in MATLAB, as a 1-
by-1 matrix or array! To see the size of a matrix or array in MATLAB, we can use
the function called size:
Functions
• A function in mathematics is any operation that produces a result that depends
only on its input. In MATLAB, as in most other programming languages (e.g., C,
C++, Java, Fortran), a function, like ‘size’, is any operation that is invoked by giving
its name

• Our input to ‘size’ was x, but in general the input to a function is given as a list of
values separated by commas inside a pair of parentheses that follows the name,
for example - plot(x,y). Each such value is called an argument.
• In the example above, size was given only one argument, x, (so no commas were
needed), and it produced as its result two numbers—1 and 1. The first 1
represents the number of rows, or height, of the matrix x, and the second 1 is its
number of columns, or width. It is possible to make larger matrices by using
brackets and semicolons (;).
• To call a function, the name of the function is given followed by the argument(s)
that are passed to the function in parentheses. Most functions then return
value(s). For example, to find the absolute value of -4, the following expression
would be entered:
• >> abs(-4)

• which is a call to the function abs. the number in the parenthesis i.e. -4, is the
argument. The value 4 would then be returned as a result.
Strings
• The term string has a special meaning in computer science. It means “sequence
of characters”.

• MATLAB stores a string as a special type of row vector and that it provides many
other built- in functions that take strings as input arguments, and we will learn
how to write our own functions that take strings as input.
Operator precedence
• Matrices, vectors, and scalars can be operated on by +, -, *, /, \, ^, and the
“dotted” versions of these operators (e.g., .*). Arbitrarily complicated expressions
can be formed by combining more than one operation, e.g.,
• >> x = a*b + c;
• >> y = c + a*b;
• >> z = a*(b + c);

• An operator’s ranking relative to other operators to determine the order in which


they are applied within an expression is called its precedence.
• Operators in an expression that includes more than one type of operator. The
highest precedence belongs to parentheses. The precedence of the arithmetic
operators, transposition, and the colon operator is given in Table below A lower
number indicates higher precedence and means that the operator is applied
earlier in the expression.
Table 1: Precedence of operators in MATLAB

PRECEDENCE OPERATOR

0 Parentheses: (...)

1 Exponentiation ^and Transpose '

2 Unary +, Unary -, and logical negation: ~

3 Multiplication and Division (array and matrix)

4 Addition and Subtraction

5 Colon operator:
Associativity
• If more than one binary operator of the same precedence occurs in an
expression, then the precedence table is no help. For example, in the expression
5-9-3, the table does not tell us whether the left - acts first or the right -. In other
words, the table does not tell us whether this expression means (5-9)-3, for which
the lefthand - acts first and which equals -7, or 5-(9-3), for which the righthand -
acts first and which equals – 1. In fact, the first one is correct.

• MATLAB’s rule for the order for applying multiple operators of the same
precedence is that the order is left-to-right. The order in which operators of equal
precedence are applied is called the associativity of the operators. Operators that
operate from left-to-right, like all those in MATLAB, are called left-to-right
associative or left-associative.
Additional Online Resources

• Introduction to Matrices and Operator -


[Link]

• Arithmetic Part 1 - [Link]

• Arithmetic Part 2 - [Link]

• Operator Precedence - [Link]


Module 1

Matrix operations, indexing


and slicing
The Colon Operator
• If the values in a vector are regularly spaced, the colon operator can be used to
iterate through these values.
• For example, 3:7 results in all of the integers from 3 to 7 inclusive:
• >> vec = 3:7
• vec = 3 4 5 6 7

• With the colon operator, a step value can also be specified by using another
colon, in the form (first:step).
• For example, to create a vector with all integers from 3 to 11 in steps of 2:
• >> svec = [Link]
• svec = 3 5 7 9 11
The linspace Function
• The linspace function creates a linearly spaced vector; linspace(x,y,n) creates a
vector with n values in the inclusive range of x to y. If n is omitted, the default is
100 points. For example, the following creates a vector with five values linearly
spaced between 3 and 15, including the 3 and 15:

• >> v = linspace(3,15,5)
• v = 3 6 9 12 15
Referring to and Modifying Elements
• The elements in a vector are numbered sequentially; each element number is called the index, or
subscript. In MATLAB, the indices start at 1. Normally, diagrams of vectors and matrices show the
indices.
• For example, for the variable vec created below, the indices 1–10 of the elements are shown
above the vector:
• vec
• 1 2 3 4 5 6 7 8 9 10
• 1 3 5 7 9 3 6 9 12 15

• A particular element in a vector is accessed using the name of the vector variable and the index
or subscript in parentheses. For example, the eight element in the vector vec is a 9.
• >> vec(8)
• ans = 9
• The expression vec(5) would be pronounced “vec sub 5,” where sub is short for
the word subscript. A subset of a vector, which would be a vector itself, can also
be obtained using the colon operator. For example, the following statement
would get the third through seventh elements of the vector vec, and store the
result in a vector variable b.

• >> b = vec(3:7)
b= 57 9 36
• Any vector can be used for the indices into another vector, not just one created
using the colon operator. The indices do not need to be sequential. For example,
the following would get the first, tenth, and fifth elements of the vector vec:

• >> vec([1 10 5])


• ans = 1 15 9
• The vector [1 10 5] is called an index vector; it specifies the indices in the original
vector that are being referenced. The value stored in a vector element can be
changed by specifying the index or subscript. For example, to change the second
element from the preceding vector b to now store the value 11 instead of 9:

• >> b(3) = 11
• b = 5 7 11 3 6
Perform Array Operations on Vectors
• MATLAB is designed to work naturally with arrays. For example, you can add a
scalar value to all the elements of an array.
• x = [1 2 3];
• y=x+2
• y=
3 4 5
• You can add any two arrays of the same size.
• z=x+y

• You can multiply or divide all the elements of an array by a scalar.


• z = 2*x
• y = x/3
• You can apply basic statistical functions in MATLAB to a vector to produce a single
output. For example, the maximum value of a vector can be determined using the
max function.
• xMax = max(x)

• MATLAB has functions that perform mathematical operations on an entire array


of values in a single command. For example, you can find the square root of each
element in array x with this syntax.
xSqrt = sqrt(x)
Matrix multiplication operators
The * operator performs matrix multiplication. So, if you use * to multiply two
equally sized vectors, you get an error message because the inner dimensions do
not agree.
• z = [3 4] * [10 20]
Error using *
Incorrect dimensions for matrix multiplication.

The .* operator performs element-wise multiplication by multiplying the


corresponding elements of two equally sized arrays.
• z = [3 4] .* [10 20]
• z=
• 30 80
Obtaining Multiple Outputs from Function
Calls
• You can apply the size function to a vector or matrix to produce a single output
variable containing the array size in a two-element row vector. The first element
is the number of rows and the second element is the number of columns.
• s = size(x)

• You can also request two output variables from the size function. In this case,
each variable contains the size of one of the dimensions of the input array. Use
square brackets ([ ]) to request more than one output.
[xrow,xcol] = size(x)
• You can find the maximum value of a vector and its corresponding index value
using the max function. The first output from the max function is the maximum
value of the input vector. When called with two outputs, the second output is the
index value.
• [xMax,idx] = max(x)

• If you need only the second output from a function, you can ignore the first
output by using a tilde (~) in its place.

• For example, you can just get number of columns in a matrix:


• [~,xcol] = size(x)

You might also like