Anda di halaman 1dari 43

MATLAB 101

Introduction to MATLAB –
Understand the basics
1

TABLE OF CONTENTS

MATLAB GUI 3
Command window 3
Workspace 4
Current folder 5
Editor window 5
Figure window 6

Variables in MATLAB 7

Arrays in MATLAB 9
Array generation 9
Types of Array 10
Array indices 11
Row vector indexing 11
Column vector indexing 11
Matrix indexing 12

Matrix operations 13
Entering data in matrice 13
Solving a system of linear equations 14
Matrix properties 18

LOOPS 20
For Loop 20
Break statement 22
Continue Statement 23
While loop 25
Relational operator 27
Logical operator 28
Difference between for and while loops 30

Control structures 30
if else command 30
Nested if structure 31
If-elseif-else structure 33
Difference between nested-if and if-elseif-else 34

Plotting 34
Line plot 34
Surface plot 36
2

Meshgrid command 36

Function 39
Calling of a function 40
Function scope 41
Nested function 41

References 42
3

MATLAB GUI

The Graphical User Interface of MATLAB has different sections and they are as follows:
● Command window
● Current folder
● Workspace
● Editor window
● Figure window

Fig 1.1 - Figure shows the different parts of MATLAB GUI

● Command window:
It is pretty much the first thing you’ll be recognizing when you first open MATLAB. The
command window displays a command prompt symbol similar to a double greater than symbol
(i.e ‘>>‘). Next to the command prompt symbol lies the cursor, where the commands are
entered. The command window is popularly referred to as an instant calculator by the MATLAB
users because when a command is executed, it instantaneously displays the answer when the
‘Enter key’ is pressed.

For example, a simple command such as ‘3+4’ is executed and the below output is shown in
command window of MATLAB.
4

Example:

>> 3+4

ans =

7
As shown, the result is stored in a variable named ‘ans’. This happens to be the default variable
in MATLAB at which a command’s result is stored if it is not assigned to a variable. To show it,
now lets execute the same command but assigning it to a variable before we execute it.

Example:

>> a = 3+4

a=

This time the result is stored in the variable assigned to it and not in ‘ans’. The ‘ans’ is
subjected to overwriting like any other variable in MATLAB. For example if we execute another
command, say ‘5*2+2’ then its result is stored in ‘ans’, which means the previous value of the
‘ans’ is overwritten by the new value.

It is sometimes annoying for all the results to be displayed or printed instantaneously in the
command window. In order to suppress that effect, the command statement is terminated
with a semicolon (i.e ‘;’)

Example:

>> b = 5*2+2;

● Workspace:
The Workspace in MATLAB contains all the variables that have been generated in the current
MATLAB session, displaying their name, value, class/data type and many more. They even
show the variables that have been generated in the script files, so they can share all the
variables. This means that when an existing variable in the script is used in the command
window, then when executing the command, the variable is overwritten.
5

For example:

>> x = 2;
>> y = 3;
>> z = x+y;

Fig 1.2 - Figure shows that the variables used are stored in workspace

The value of the above variables are shown in the workspace. The workspace keeps updating
with new variables and their values as they are introduced in the editor or command windows.

● Current folder:
In the Current folder, all the files which are stored in it are listed as shown in the figure 1.1. It is
important to note that, in order to run any file, it must be either in current folder or on the
search path. A quick way to view or change the current folder or its contents is by using the
search path field in the MATLAB toolbar.

● Editor window:
In order to create a proper program, which can be edited, saved and opened whenever needed,
the editor window is used. The programs created using the editor window are automatically
assigned '.m’ extension and it is called as an ‘M - File’.
6

A new script file can be created by clicking on the Editor tab and then the ‘New Script’ icon. In
order to open an existing script file, ‘open’ icon is used. for saving the script File, the save icon
should be used.

Fig 1.3 - Figure shows the different parts of editor window

In the editor window, different features of the MATLAB language are displayed in different
colours. Like, comments are displayed in green, variables and numbers in black, character
strings in red/purple, and the MATLAB keywords appear in blue.

● Figure window:
A figure window appears when any plot function is used in the command window or when a
script file which contains the plot function is executed. For example the following commands are
given in the command window for plotting a sine function and the output is displayed in the
figure.

For example:

>> x=0:0.05:20;
>> y=sin(x);
>> plot(x,y);
7

Fig 1.4 - Figure shows the output for above example in figure window

● Variables in MATLAB

A variable in programming, is simply a name given to any data, so that it would be useful in
addressing the data when necessary. In traditional programming languages, it is necessary to
mention the variable and its data type before initiating the commands. But in MATLAB, it is not
necessary to mention the data type of the variable, MATLAB recognizes the data type,
according to the value assigned to it.
The basic form of data in MATLAB is an array. Even a single element of data is considered
an array of size 1x1 (i.e. row x column). The array in MATLAB has the capacity to contain
several elements of the same data type.
There are 16 fundamental data types or classes in MATLAB. Some of them are, int8, uint8,
int16, uint16, int32, double, single, char, string, etc. The data type double, is a double precision
array and is the most common data type in MATLAB, because MATLAB computations are
normally done in double precision.
8

There are some important points one has to keep in mind before assigning data to a variable,
they are as follows:

● The first letter of a variable should be an alphabet, and it may be followed by a number
or underscore.

● The variable name that contains more than one word, should not be separated by a
blank space. Instead an underscore should be used in between the words. For
example, if we want to use a variable called ‘physical state’, it can used as
‘physical_state’.

● MATLAB is case sensitive. Lower and uppercase letters represent two different
variable names. For example, ‘count’ and ‘COUNT’ represent two different variables.

● Words such as for, while, switch, and function should not be used, as they represent
some of the key constructs of a programming language which are called ‘Keywords’.

Fig 1.5 - FIgure shows the variable’s info using ‘whos’ command

In the above image, ‘a’ is the variable name and the value ‘5’ is an integer constant.The ‘whos’
command is used to print all the variables, its data types and their sizes in the command
window. Here we can see that the data type recognised by MATLAB for the variable ‘a’ is
double and the size of the variable is ‘1x1’, which is single element but considered as a 1x1
array.
9

ARRAYS IN MATLAB
An array is a kind of structure, in which a group of elements are contained in an orderly fashion.
The elements can be arranged in the form of a row, a column, an ’n’ dimensional matrix or even
a 1x1 matrix. All these forms are called an Array.

Scalar - a scalar is a 1x1 matrix containing a single element only.

Example: a = 5;

Here the value ‘5’ has a size of 1x1. Hence ‘a’ is a scalar.

● Array generation:
Arrays could be generated by various methods, they are as follows:

- Using concatenation operator

‘[ ]’ is the concatenation operator. Elements of the same row are separated by blank space or
comma. Different rows of the matrix are separated by a semicolon.

Example:

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


2. B =[1,2,3]
3. C=[1;2;3]

- Using range operator

A row vector with evenly spaced elements can be created by the following command

Syntax: variable_name = k : l : m

Where k is the initial value, l is the increment and m is the final value

Example:

>> J = 1:2:10

J=

1 3 5 7 9
10

Here the initial value is incremented by 2 and so the end value of the row vector is 9 rather than
10. Because after 9 the next number would be 11, but it is not within the range so its not printed.

- Using Linspace command

The ‘linspace’ command is also used to generate a row vector. The general syntax is as
follows,

Syntax: variable_name = linspace(x1,x2,n)

It generates ’n’ equally spaced elements between numbers x1 and x2.

Example:

>> K = linspace(1,10,5)

K=

1.0000 3.2500 5.5000 7.7500 10.0000

● Types of Array:

1D array - A one dimensional array contains a number of elements arranged row-wise or


column-wise. It can also be called as a row vector if elements are arranged row-wise or called
as a column vector if elements are arranged column-wise. 1xN is the size of a row vector of one
row and N columns. 1xM is the size of a column vector of M rows and one column.

Example:

>> x=[1 2 3]

x=

1 2 3

>> y=[1;2;3]

y=

1
2
3
11

Here x is a row vector and y is a column vector.

2D array - A two dimensional array is also called a matrix of ‘M' rows and ’N’ columns.
Here the array contains M number of rows and N number of columns.

For example:

>> z=[1 2;3 4]

z=

1 2
3 4

Here the variable ‘z’ is 2x2 matrix

● Array indices:
In order to access or specify a particular element or a subset of matrix then the array indexing
could be used. A(i,j) is an array index, where 'i' refers to the row number and ‘j’ refers to the
column number. The array index A(i,j) refers to the ‘i’th column and ‘j’th column of the array A.
For example A(2,3) refers to the element in the second row and 3rd column of the matrix.

● Row vector indexing:

>> a = [1 2 3 4 5] ---> here the variable has been assigned

a=

1 2 3 4 5

>> a(1,3) ---> this command returns the element in the first row and third
ans = column

● Column vector indexing:

>> b = [1;2;3;4;5] ---> here the variable has been assigned

b=
12

1
2
3
4
5

>> b(4,1) ---> this command returns the element in the fourth row and first column

ans =

● Matrix indexing:

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

c=

1 2 3
4 5 6
7 8 9

>> c(2,1) ---> this command returns the element in the second row and first column

ans =

Sub-matrices or Sub-arrays could also accessed by specifying the dimension of the sub-
matrix with respect to the source matrix. The general syntax is A(i:j,k:h), where ‘i’ is the start
value of the row number range, 'j' is the end value and ‘k' refers to the star value of the column
range, ‘h’ is the end value.

For example: ‘d’ is a matrix of dimension 3x3 and we are supposed to access the elements that
intersect in the first two rows and first two columns.

>> d = [2 6 4;4 5 3;3 5 2]

d=

2 6 4
4 5 3
3 5 2
13

>> d(1:2,1:2) ---> the first two elements in first row and second row are accessed

ans =

2 6
4 5

Here the command d(1:2,1:2) is used to access the required elements. The colon (i.e ‘:’)
represents the range operator.

The array indexing can be done by another method. Consider the array as one long column
vector, which is formed from the columns of a given matrix. The element in ‘i’th row and ‘j’th
column of (mxn) matrix A, may be obtained with a single index k = (j-1)m + i. For example,
element d(1,2) of (3x3) matrix of d, where m=3, n=3, i=1, j=2, can be accessed by using the
index k = (2-1)*3+1, i.e k=4 and d(6) will access the same element as d(2,3).
therefore the element is 3.

The matrix ‘d’ could be assumed as one single column of elements,

d=2 ---> assumed matrix form


6
4
4
5
3
3
5
2

Here the 6th element is needed and it is called using the command ‘d(6)’. This gives the 6th
element from the top, which is 3.

MATRIX OPERATIONS
A matrix is simply a two dimensional array of ‘M’ rows and ’N’ columns. it contains M*N
elements.

● Entering data in matrice:

- Start with a left-handed square bracket ‘[‘.


- Type the matrix elements row wise. Each row vector should have the same length to
create a valid matrix.
14

- Enter the elements of the first row with one or more blanks or a comma separating each
element.
- Separate the different rows of the matrix by a semicolon (;)
- Enclose the entire list of elements of the matrix within square brackets.

A row vector could be created by any one of the array generating methods. For example, a row
vector could be created by entering numbers within square brackets and having a blank space
or comma before very successive element. This is just one of the methods to create a row
vector. It can also be created using linspace command and the range operator.

A column could be created by entering the numbers within square brackets and having a
semicolon before every successive element. Another way is to press the enter key after entering
every element within the square brackets.

Example:

>> H = [1;2;3;4]

H=

1
2
3
4

>> I = [1
2
3
4]

I=

1
2
3
4

● Solving a system of linear equations:

The methods to solve a system of linear equations are:


15

- Using inverse command

A system of linear equations could be solved using inverse command by implementing the
following steps,

● Create a square matrix containing the coefficients of the unknowns, of each equation, in
separate rows. If nxn is the size of the square matrix, n is the number of unknowns.

● Create a column vector of the constants in the right-hand side.

● Find the inverse of the coefficient matrix using the command ‘inv(variable_name)’.

● Matrix multiplication of the coefficient matrix and the constant vector should be done.

● This results in a column vector containing the numerical value for all the unknowns.

For example:

Let us consider a set of linear equations,

Eqn 1: x + 2y + 3z = -5
Eqn 2: x - 3y = 3
Eqn 3: 2x = 0

The above set of linear equations could represented in the matrix form as follows,

A= 1 2 3 ; X= x ; B = -5
1 -3 0 y 3
2 0 0 z 0

Here,
Matrix A contains the coefficients of the unknowns,
Matrix X contains the unknown,
Matrix B contains the constants of the linear equations.
16

Fig 1.6 - Figure showing usage of inverse command for solving set of linear equations

The above figure shows the solving of a system of example linear equations. The numerical
values of the unknowns are seen in the command window.

- Using mldivide command:

The ‘mldivide’ command is equivalent to the right division of the A matrix and B vector, that is,
mldivide(A,B) = A\B

Syntax: X = mldivide(A,B)
17

Fig 1.7 - Figure showing usage of mldivide command

- Using linsolve command

It is yet another function provided by MATLAB to solve a system of linear equations. the syntax
is as follows,

Syntax: X = linsolve(A,B)
18

Fig 1.8 - Figure showing usage of linsolve command

● Matrix properties:
MATLAB has built-in functions to calculate many of the matrix properties such as determinant of
a matrix, rank of a matrix, etc.

Let us consider a matrix A = 1 2


0 4

● Determinant of a matrix

Syntax - det(A)

It returns the determinant of a given square matrix A.

Example:

>> det(A)

ans =

4
19

● Rank of a matrix

Syntax - rank(A)

It returns the rank of a given rectangular matrix A.

Example:

>> rank(A)

ans =

● Trace of a matrix

Syntax - trace(A)

It returns the sum of the principal or leading diagonal elements of a rectangular matrix A

Example:

>> trace(A)

ans =

● Transpose of a matrix

Syntax - A’

It returns the transpose of the specified rectangular matrix A

Example:

>> A'

ans =

1 0
2 4
20

● Eigenvalue of a matrix

Syntax - eig(A)

It returns the eigenvalues of matrix A

Example:

>> eig(A)

ans =

1
4

There are many other built-in functions in MATLAB which can be used to calculate many other
matrix properties.

LOOPS

● For Loop:
A ‘loop’, in general, refers to anything whose start and end points are connected.
That is, once you begin from the start point and proceed further, you will reach the finish line just
to find that it once again guides you to the same point where you started. Proceeding further
means that you are repeating your same action again & again.

Now, in programming point of view, a ‘loop’ is a set of instructions or commands that


repeats itself for a specified number of times (in case of ‘For loop’) or until the user stated
condition becomes false (in case of ‘While loop’).

Syntax: for variable_name = initial value : increment value : final value

Statement 1;
Statement 2;

end

In loop command, the part of the command following the “=” is called ‘statement’ where we
mention the number of times the group of statements needs to be executed.
Any loop must contain “end” statement (in the case of MATLAB) or “endfor” (in the case
OCTAVE) to symbolize the end of our set of instructions so the program again checks the
condition to repeat the process.
21

Example 1 -

Problem - Code a program to display all the integers from 1 to 10.

Solution -

Fig 1.9 - Figure shows the code for example 1 using disp() command

Explanation -
Here we have repeated the same command “disp(value)” 10 times to do the job.

But, knowing that same command is to be repeated, we can get this job done simply with 3
lines of code by using a loop as shown below :
22

Fig 2.0 - Figure shows the usage of for loop

Line 1 : for i =1:10 - initiates the loop


- states a condition for which the instruction is to be repeated.
- Our condition being the value to be 1 through 10, the variable “i” is
initiated.

Line 2 : disp(i) - instruction


- this command displays the value of “i” in command window.

Line 3 : end - end of loop.


- this terminates the set of instruction and takes the the program again to
Line 1.
- The process is repeated for the mentioned number of times

● Break statement:
Just as the name suggests, a break statement breaks the loop and prevents
the program from executing succeeding commands within the loop.
Putting in simpler words, a program that encounters a “break” statement stops any further
iterations of the commands in that particular loop.
23

Example :

Fig 2.1- Figure shows the usage of break command in for loop

Explanation :
In the afore explained program, addition of a break statement, terminated further
iteration of the loop. The program first entered the loop as the first condition was satisfied and
executed the first command - “disp (i)” and gave output of displaying our stated initial value of “i”
which is 1.

After executing the first command, the program encountered “break” statement due to which it
stopped any further iterations of the loop.

● Continue Statement:

A Continue command in a loop stops execution of succeeding commands within the loop for
that particular iteration.
24

Example :

Fig 2.2 - Figure shows the usage of continue command

Explanation :

Once again, the same program with which we explained “for” loop has been used but by adding
a “ continue” command before the “disp (i)” command.

Now the program first entered the loop as the first condition was satisfied. But when the
program encountered “continue” command, it stopped execution of succeeding commands
within the loop for that particular iteration. Then when it goes for next iteration, it encounters
same command above any other commands. So it keeps on skipping the iteration until the
stated condition becomes false and the program itself skips that loop.

To make this more clear let us have another example.


25

Example 2:

Fig 2.3 - Figure shows usage of continue command

This is the same program explained before but with addition of a “disp (‘content’)” before the
continue statement of the loop.
In this program the command before “continue” statement was executed for every iteration
but not that “disp (i)” command as it follows the “continue” statement which makes the program
to skip to next iteration without executing any succeeding commands in that loop.
The program iterates the loop for stated number of times and gives the output which shows
that only the command prior to “continue” statement was executed.

● While loop:
While loop is used when the user does not know how many times the set of actions have to be
repeated, but a condition at which the loop should stop is known.

Syntax: while condition


Statement 1;
Statement 2;
end

The condition consists of a counter, which is a variable, whose value should be assigned before
the execution of the loop. If the counter variable satisfies the condition, then the loop gets
executed, if not then the loop will not execute. It is necessary to give a update command,
such as the increment or decrement of the counter variable, or else the loop will go on
for an infinite number of loops.
26

non empty and contains only nonzero elements


( logical or real numeric ). Otherwise, the condition is ‘False’.

Example 1 -

Problem - Create a code that displays numbers starting from a random number incremented
by 0.1 upto 1.
Solution -

Fig 2.4 - Figure shows the code for example 1 of while loop

Explanation -
Here we do not know the initial value but we need to increment it by 0.1 every
time and display it until the value is less than 1.
In this case, we are aware of only a condition but no idea about how many
iterations that my initiated value would take before it equals 1.
In such situations where we are unaware of number of iterations,we can use “while” loop
coupled with a logical expression of our condition.

Line 4 : i=rand; - our value is initiated to be a random value.


- by default, a random value initiated in MATLAB will be
27

Between 0 and 1.

Line 5 : while i<1 - initiated our while loop along with logical expression of our
situation.
- our situation being to iterate the command only until value of i
becomes 1, it is expressed as “ i<1”.

Line 6 : disp (i) - our main command that needs to be repeated until our condition
becomes false.
- this command,on execution, displays the current value of “i”.

Line 7 : i=i+0.1; - this command increases the value of “i” by 0.1 each time the loop
is
executed.
- this satisfies our problem requirement.

Line 8 : end - this denotes the end of loop, from where the program once again
enters into Line 5 where the loop is started and evaluates the
logical expression with current “i” value.

As you can see in the picture, our program started with a random value assigned for “i” and
iterated the command for displaying the value of “i” which is incremented by 0.1 for every
iterations until the value reached “0.9940” from which further increment will result in a value
more than 1. This disapproves our logical condition and terminates any further iterations.

Any number of conditions can be logically expressed for the program as per requirement.

Note: In the ‘for’ and ‘while’ loops, the conditions mostly comprise of relational and logical
operators. Let us look at a few relational and logical operators.

● Relational operator:

Operator Operation

< Less than

<= Less than or equal to

> Greater than

>= Greater than or equal to


28

== Equal to

~= Not equal to

● Logical operator:

Operator Operation

&& && (AND) returns 1 if both elements are true


(non - zero) and returns 0 if any one element
is 0

|| || (OR) returns 1 if any element is 1 and


returns 0 if both elements are 0

~ ~ (NOT) takes only one input. Returns 1 if the


input element is 0 and returns 0 if the input
element is 1

Example 2 :

Problem -
Create a code that displays numbers starting from a random number greater than 0.2
incremented by 0.1 upto 1.

Solution -
Our expression of condition needs an alteration as “ i>0.2 && i<1 ”
The part “&&” denotes logical ‘and’ statement.
29

Fig 2.5 - Figure shows the code for example 2

Example 3 -

Problem -
Create a code that displays numbers starting from a random number greater than 0.2
or greater than 0.6. Increment by 0.1 in each iteration but stop when value gets greater than 1.

Solution -
Our expression of condition needs an alteration as “ i>0.2 || i>0.6 ”
The part “||” denotes logical ‘or’ statement.

Fig 2.6 - Figure shows the code for example 3


30

Here the condition being to execute the command on satisfy any one of the given condition,
The same has expressed logically in the expression part.

Afore explained “break” statement has been used here to terminate the execution of loop when
value gets beyond 1.

● Difference between for and while loops:

The difference between for and while loops, is in the usage. One uses ‘for’ loop if the number of
repetitions are known and one uses ‘while’ loop when the number of repetitions are not
known but a condition at which the iteration should stop, is known.

CONTROL STRUCTURES

● if else command:

The if - else conditional statement is an extension of the if conditional statement. In the if


statement, the group of statements inside the block get executed only if the condition is true, but
in if-else, another group of statements get executed when the condition is false. if - else
conditional statement is used when we have a binary condition and separate commands should
get executed when the condition is true or false.

Syntax:

if expression
statement 1
statement 2
.
.
.
end

else
statement 1
statement 2
.
.
end
Note: In the expressions, the logical operators such as AND, OR and NOT could be used.
31

Problem statement: Write a program to evaluate y = 2x +1 if x<5, otherwise y = 2x.

Code:

Fig 2.7 - Figure shows the code using an if-else control structure

Explanation:

As we can see in the above image,


When x = 7, which is greater than 5, the condition is true. so y = 2x+1 gets executed.
When x = 2, which is less than 5, the condition is false. so y = 2x gets executed.

● Nested if structure:
Nested if structure simply means nesting or including another if structure in a pre-existing if
structure. So there is a if structure, inside another if structure. These nested if structures are
mostly used when a number of conditions are to be checked before executing a particular set of
statements.

Syntax:

if condition 1
Statement 1
32

Statement 2

if condition 2
Statement 1
Statement 2

end -----> ( this ends the if structure with condition 2)

Statement 3 -----> (remaining statements of the first if structure)


Statement 4

end ------> ( this ends the if structure with condition 1)

Example: Write a program to add the two given numbers if they are less than 3 and greater
than 1

Code:

a = input('enter the number:');


if a<3
disp('a is less than 3');
if a>1
disp ('and a is between 1 and 3');
end
end

Output:

When number is 2,

enter the number:2


a is less than 3
and a is between 1 and 3

When number is 0,

enter the number:0


a is less than 3
33

● If-elseif-else structure:
This control structure allows the user to check a large number of different conditions and
executes a particular set of statements for every condition.

Syntax:

if condition 1
Statement 1
Statement 2
.
.
elseif condition 2
Statement 1
Statement 2
.
.
else
Statement 1
Statement 2
.
.
end

Example: write a program to check whether a given number is greater than or equal to 50.

Code:

a = input('enter the number:');


if a>50
disp('the number is greater than 50');
elseif a==50
disp('the number is equal to 50');
else
disp('the number is smaller than 50');
end

Output:

When number is: 23,

enter the number:23


the number is smaller than 50

When number is: 50


34

enter the number:50


the number is equal to 50

When number is: 53

enter the number:53


the number is greater than 50

● Difference between nested-if and if-elseif-else:


Nested if basically executes the set of statements inside the nested if only if the condition
imposed by the primary if structure and the nested if structure, are true. In if-elseif-else, each set
of statements get executed when the corresponding condition in the ‘if’ or ‘elseif’ is true.

PLOTTING

● Line plot:
A line plot represents a mathematical function. It shows how the function changes with respect
to the input argument. The trend of any variable that depends on an independent variable (e.g
time or frequency) could be shown graphically using line plots.

Syntax: plot(x,y)

The above is the basic syntax to draw a line plot. Add-ons such as line colour, line width,
markers, etc could be used by naming them between apostrophes (i.e ‘ ‘) and mentioning their
respective values next to them.

Example: plot(x,y,’color’,’r’,’linewidth’,3,’marker’,’o’)

Here the value ‘r’ next to ‘color’ means red and ‘o’ means all the coordinates will be marked by
a circle. The different style options for the plot are given below,

Color code Color Marker style Marker style Line style Line style
code code

y yellow . point - Solid line

m magenta o circle : Dotted line

c cyan x x-mark -. Dashdot line


35

r red + plus -- Dashed line

g green * star

b blue s square

w white d diamond

k black p pentagram

Problem statement:
Create a program to plot the graph between variable-y vs variable-x, where y = x^2. the line plot
must be red in colour and each coordinate point must be represented by a star marker style.

Output:

Fig 2.8 - Figure shows the code for generating a line plot with required style options

Explanation:

Line 1 - The variable x is assigned its respective values using the range operator.
36

Line 2 - The variable y is represented as a function of x.

Line 3 - The plot command is used to plot a line graph between variables x and y. Since we are
supposed to represent the line in red colour and each coordinate point in the form of an asterisk,
the colour and line style options are used.

● Surface plot:
For visualization of data in three dimension, MATLAB provides a number of functions. To
display data which is a function of two independent variables, the surface plots are used.

For example, we are supposed to represent the drag force acted upon an person running
through air at a uniform acceleration and his frontal area keeps on changing. Assume here the
velocity changes and the drag coefficient value changes uniformly. So the drag force changes
with respect to velocity and the drag coefficient. So in order to represent the drag force
graphically, we can use the surface plot.

Syntax: surf(x,y,z)

Here x and y are 2D arrays which have been converted from their corresponding 1D arrays
using the meshgrid command. And z is the function of x and y.

● Meshgrid command:
As said before, the meshgrid command is used to transform a one dimensional array into two
dimensional array, which can be used for evaluation of the functions of two variables and 3D
surface plots.

Syntax: [X,Y] = meshgrid(Xbegin : Xinc : Xend, Ybegin : Yinc : Yend)

For example, Lets create 2D grid coordinates with x-coordinates defined by the vector x and y-
coordinates defined by the vector y.

>> x = 1:4;
>> y = 1:6;
>> [xx,yy]=meshgrid(x,y)

xx =

1 2 3 4
1 2 3 4
1 2 3 4
1 2 3 4
37

1 2 3 4
1 2 3 4

yy =

1 1 1 1
2 2 2 2
3 3 3 3
4 4 4 4
5 5 5 5
6 6 6 6

Problem statement:
Create a surface plot of the function f(x,y) = 8 - x^2 -9y^2, over the interval x = 1 to 10 in 20
equal parts and y = 1 to 10 in 20 equal parts.

Code:

Fig 2.9 - Figure shows the code for generating a 3D surface plot
38

Output:

Fig-3.0 - Figure shows the output for surf command

Explanation:

Line 1 - 1D array of x values are initialised

Line 2 - 1D array of y values are initialised

Line 3 - x and y are converted to a 2D array by using meshgrid command and their values are
stored in xx and yy.

Line 4 - The values of the function are assigned to zz variable

Line 5 - ‘surf’ command is used to plot the 3D Surface plot


39

FUNCTION

A function in MATLAB is similar to the script files in MATLAB, but with certain differences.The
function accepts input arguments and returns output arguments. The function starts with the
function definition line. The syntax of the function definition is as follows,

Syntax: function [out1,out2] = function_name(inp1,inp2)

Here,

function is a keyword
out1,out1 are output arguments
inp1,inp2 are input arguments

Fig 3.1 - Figure show the different sections of a function definition line

The same rules which apply to the naming of variables, apply to function naming also.
Function names must begin with a letter and the remaining characters can be any combination
of letters, numbers and underscores. One important rule is that the function filename and
the function name should match, or else MATLAB ignores the function name.
40

● Calling of a function:

The function is called in the command window, which invokes the function. It is enough to
mention the function name and the input arguments for calling the function.

Example: function_name(inp1,inp2)

Its is not necessary to use the same input variable names used in the input arguments
section, any name could be used while calling. MATLAB recognises only the position of the
input variable or the input value to the one mentioned in the function definition line.

For example, let’s write a function execute an mathematical expression,

In Function window:

function [result] = example(inp1,inp2)


result = (inp1).^2 + inp2;
end

In Command window:

>> input1 = 2:6

input1 =

2 3 4 5 6

>> input2 = 1:5

input2 =

1 2 3 4 5

>> example(input1,input2) ---> here though the input variable names are different, but
they get executed.
ans =

5 11 19 29 41

Here we have mentioned totally different variable names while calling the function in the
command window, yet it executed.
41

● Function scope:

Any variable initiated inside a function, has its influence only inside that function. Function files
treat the internal variables as local to that function and have their own workspace. This
means that the variables in a function cannot be seen in the workspace, because they take
separate memory space in MATLAB. Each function we create has its own workspace where it
stores its own variables.

Fig 3.2 - Figure shows that an error is thrown when a variable inside is called in
command window

In the Above image, when an expression such as c = 2*f is typed in command window, it
returns an error, stating "Undefined function or variable 'f’.”. Because the variable ‘f’ is not
available in the workspace shared by the command window and the script file. Any variable
initiated in the command window or script file is called as a global variable and the variables
initiated in the function are called a local variables.

● Nested function:
Just as a ‘for’ loop may be nested within another ‘for’ loop, a function may also be nested
within another function. The nested functions provide a way to pass information, without
passing it through input / output arguments and without using global variables.
42

The basic form of a nested function is given below,

function [out1,out2] = primary_function(in1,in2) ---> (code for the primary function)


---
--- --->(statements for the primary function)
---
function [out11,out22] = nested_function(in11,in22) --->(code for the nested function)
---
---
---
end --->(end of nested function)
--- --->(remaining statements of primary function)
---
end --->(end of primary function)

The syntax for the nested function remains the same as for a normal function.

REFRENCES

- “MATLAB and its applications in engineering”, raj kumar bansal, Ashok kumar
goel, Manoj kumar sharma, PEARSON publications.
- https://in.mathworks.com/help/matlab/

Anda mungkin juga menyukai