Matlab Q&a
Matlab Q&a
Matlab Q&a
UNIT - I
INTRODUCTION TO MATLAB
1 a Define MATLAB and explain its features.
MATLAB (short for MATrix LABoratory) is a special-purpose computer program optimized to perform
engineering and scientific calculations. It started life as a program designed to perform matrix
mathematics, but over the years it has grown into a flexible computing system capable of solving
essentially any technical problem. The MATLAB program implements the MATLAB programming
language and provides a very extensive library of predefined functions to make technical programming
tasks easier and more efficient.
The MATLAB program is a combination of a procedural programming language, an integrated
development environment (IDE) that includes an editor and debugger, and an extremely rich set of
functions that perform many types of technical calculations. The MATLAB language is a procedural
programming language, meaning that the engineer writes procedures, which are effectively mathematical
recipes for solving a problem. This makes MATLAB very similar to other procedural languages such as
C or Fortran. However, the extremely rich list of predefined functions and plotting tools makes it
superior to these other languages for many engineering analysis applications. In addition, the MATLAB
language includes object-oriented extensions that allow engineers to write object-oriented programs.
These extensions are similar to other object-oriented languages such as C++ or Java.
MATLAB system features are as follows:
1. The MATLAB Language: This is an high level matrix/array language with the control flow
statements, functions, data structures, input/output and object –oriented programming features.
2. The MATLAB working environment: This is the set of tools and facilities that you work with as the
MATLAB user or programmer. It includes facilities for managing the variables ion your workspace and
importing and exporting data. It also includes tools for developing, managing, debugging, profiling, M-
files and MATLAB’s applications.
3. Handle Graphics: This is the MATLAB graphics system. It includes high-level commands for two
dimensional and three-dimensional data visualisation, image processing, animation and presentation
graphics. It also includes low level commands that allow you to fully customise thje appearance of
graphics as well as to build complete graphical use interface on your MATLAB applications
4. The MATLAB mathematical function library: This is vast collection of computational algorithms
ranging from elementary functions like sum, sine cosine, and complec arithmetic, to more sophisticated
functions like matrix inverse, matrix eigenvalues, Bessel functions and fast fourier transforms
5. The Matlab Applications Program Interface (API): This is library that allows you to write C and
Fortran Programs that interact with MATLAB. Kt includes facilities for calling routines from
(MATLAB (dynamic linking), calling MATLAB as a computational engine, and for reading and writing
MAT files.
6. Toolboxes: The toolboxes are an extension to the basic Matlab system by providing access to
additional mathematical function library on specific topics. The following are some of the toolboxes
a) Communication toolbox
b) Control tool box
c) DSP Blockset
d) Symbolic Math Toolbox
e) Financial Toolbox
f) Fuzzy Logic Toolbox
g) Image Processing Toolbox etc.
b Explain how to solve linear algebraic equations by using MATLAB, give one example.
Course Code: 20EC0454 R20
MATLAB provides the left division method for solving the linear algebraic equation set Ax = b. This
method is based on Gauss elimination. To use the left division method to solve for x, you type x = A\b.
Use the left division method to solve the following set.
3x1 + 2x2 - 9x3 = -65
-9x1 - 5x2 + 2x3 = 16
6x1 + 7x2 + 3x3 = 5
The matrices A and b are
3 2 −9 −65
𝐴 = [−9 −5 2 ] and B=[ 16 ]
6 7 3 5
The session is
>>A = [3,2,-9;-9,-5,2;6,7,3];
>>rank(A)
ans =
3
Because A is 3 x 3 and rank(A) = 3, which is the number of unknowns, a unique solution exists. It is
obtained by continuing the session as follows.
>>b = [-65;16;5];
>>x = A\b
x=
2.0000
-4.0000
7.0000
This answer gives the vector x, which corresponds to the solution x1= 2, x2=4, x3 = 7
For the solution x =A-1 b, vector x is proportional to the vector b. We can use this linearity property to
obtain a more generally useful algebraic solution in cases where the right-hand sides are all multiplied by
the same scalar. For example, suppose the matrix equation is Ay = bc, where c is a scalar. The solution is
y =A-1 bc = xc. Thus if we obtain the solution to Ax = b, the solution to Ay =bc is given by y= xc.
2 a What are the good programming practices for MATLAB?
Every MATLAB program should be designed so that another person who is familiar with MATLAB can
easily understand it. This is very important, given that a good program may be used for a long period of
time. Over that time, conditions will change, and the program will need to be modified to reflect the
changes. The program modifications may be done by someone other than the original programmer. The
programmer making the modifications must understand the original program well before attempting to
change it. It is much harder to design clear, understandable, and maintainable programs than it is to
simply write programs. To do so, a programmer must develop the discipline to properly document his or
her work. In addition, the programmer must be careful to avoid known pitfalls along the path to good
programs. The following guidelines will help you to develop good programs:
1. Use meaningful variable names whenever possible. Use names that can be understood at a glance, like
day, month, and year.
2. Create a data dictionary for each program to make program maintenance easier.
3. Use only lower-case letters in variable names, so that there won’t be errors due to capitalization
differences in different occurrences of a variable name.
4. Use a semicolon at the end of all MATLAB assignment statements to suppress echoing of assigned
values in the Command Window. If you need to examine the results of a statement during program
debugging, you may remove the semicolon from that statement only.
5. If data must be exchanged between MATLAB and other programs, save the MATLAB data in ASCII
format. If the data will only be used in MATLAB, save the data in MAT-file format.
6. Save ASCII data files with a “dat” file extent to distinguish them from MAT-files, which have a “mat”
file extent.
7. Use parentheses as necessary to make your equations clear and easy to understand.
8. The MATLAB language is case sensitive, which means that uppercase and lowercase letters are not
the same. Thus the variables name, NAME, and Name are all different in MATLAB. Be sure to
capitalize a variable exactly the same way each time that it is used. It is good practice to use only
lowercase letters in variable names.
9. Always use the proper number of dimensions when addressing a multidimensional array.
10. Be sure to distinguish between assigning values to a subarray and assigning values to an array.
MATLAB behaves differently in these two cases.
Course Code: 20EC0454 R20
11. Always include the appropriate units with any values that you read or write in a program.
12. Follow the steps of the program design process to produce reliable, understandable MATLAB
programs.
13. Be cautious about testing for equality with numeric values, since roundoff errors may cause two
variables that should be equal to fail a test for equality. Instead, test to see if the variables are nearly
equal within the roundoff error to be expected on the computer you are working with.
14. Use the & AND operator if it is necessary to ensure that both operands are evaluated in an
expression, or if the comparison is between arrays. Otherwise, use the && AND operator, since the
partial evaluation will make the operation faster in the cases where the first operand is false. The &
operator is preferred in most practical cases.
15. Use the | inclusive OR operator if it is necessary to ensure that both operands are evaluated in an
expression or if the comparison is between arrays. Otherwise, use the || operator, since the partial
evaluation will make the operation faster in the cases where the first operand is true. The | operator is
preferred in most practical cases.
16. Always indent code blocks in if, switch, and try/catch constructs to make them more readable.
17. For branches in which there are many mutually exclusive options, use a single if construct with
multiple elseif clauses in preference to nested if constructs.
b Describe input and output commands used in MATLAB.
Controlling Input and Output MATLAB provides several useful commands for obtaining input from the
user and for formatting the output (the results obtained by executing the MATLAB commands). Table 1
summarizes these commands.
Table 1 Input/output Commands
The disp function (short for “display”) can be used to display the value of a variable but not its name. Its
syntax is disp(A), where A represents a MATLAB variable name.
The disp function can also display text such as a message to the user. You enclose the text within single
quotes.
For example, the command disp(‘The predicted speed is:’) causes the message to appear on the screen.
This command can be used with the first form of the disp function in a script file as follows (assuming
the value of Speed is 63):
disp(‘The predicted speed is:’)
disp(Speed)
When the file is run, these lines produce the following on the screen:
The predicted speed is: 63
Input Function
The input function displays text on the screen, waits for the user to enter something from the keyboard,
and then stores the input in the specified variable. For example, the command
x = input(‘Please enter the value of x:’)
causes the message to appear on the screen. If you type 5 and press Enter, the variable x will have the
value 5.
3 a What do you understand by debugging and what types of errors occur in MATLAB
programming?
Errors in programs are known as bugs, and the process of locating and eliminating them is known as
debugging. Given that we have written a program and it is not working, how do we debug it?
Three types of error are found in MATLAB programs.
Syntax Error:The first type of error is a syntax error. Syntax errors are errors in the MATLAB
statement itself, such as spelling errors or punctuation errors. These errors are detected by the MATLAB
compiler the first time that an M-file is executed. For example, the statement
Course Code: 20EC0454 R20
X = (y+3)/2)
contains a syntax error because it has unbalanced parentheses. If this statement appears in an M-file
named test.m, the following message appears when test is executed.
» test
??? x = (y + 3) / 2)
|
Missing operator, comma, or semi-colon.
Error in ==> d:\EEE\matlab\debug\test.m
On line 2 ==>
Run Time Error: The second type of error is the run-time error. A run-time error occurs when an illegal
mathematical operation is attempted during program execution (for example, attempting to divide by 0).
These errors cause the program to return Inf or NaN, which is then used in further calculations. The
results of a program that contains calculations using Inf or NaN are usually invalid.
Logical Error: The third type of error is a logical error. Logical errors occur when the program
compiles and runs successfully but produces the wrong answer.
Typographical Error: The most common mistakes made during programming are typographical errors.
Some typographical errors create invalid MATLAB statements. These errors produce syntax errors that
are caught by the compiler. Other typographical errors occur in variable names. For example, the letters
in some variable names might have been transposed, or an incorrect letter might be typed. The result will
be a new variable, and MATLAB simply creates the new variable the first time that it is referenced.
MATLAB cannot detect this type of error. Typographical errors can also produce logical errors. For
example, if variables vel1 and vel2 are both used for velocities in the program, then one of them might
be inadvertently used instead of the other one at some point. You must check for that sort of error by
manually inspecting the code.
b Consider the following set of equations and Write MATLAB script to solve it.
6x - 4y + 8z = 112
-5x - 3y + 7z = 75
-5x - 2y + 4z = 25
A 3X3 set of given simultaneous linear equations takes the form
Ax=B
Where
6 −4 8 112 𝑥1
A= [−5 −3 7] and B= [ 75 ] x = [𝑥2]
−5 −2 4 25 𝑥3
-1
To solve the equation solve x = A B
Since the left division operator A\B is defined to be inv(A) * B, the left division operator solves a system
of simultaneous equations in a single statement!
4 a What is the purpose of the MATLAB command window, edit window and figure window?
The Command History Window displays a list of the commands that a user has entered in the
Command Window. The list of previous commands can extend back to previous executions of the
program. Commands remain in the list until they are deleted. To reexecute any command, simply
double-click it with the left mouse button. To delete one or more commands from the Command History
window, select the commands and right-click them with the mouse. A popup menu will be displayed that
allows the user to delete the items.
The Start Button : The Start Button allows a user to access MATLAB tools, desktop tools, help files,
and so on. It works just like the Start button on a Windows desktop. To start a particular tool, just click
on the Start Button and select the tool from the appropriate submenu.
Course Code: 20EC0454 R20
An Edit/Debugger Window: An Edit Window is used to create new M-files, or to modify existing ones.
An Edit Window is created automatically when you create a new M-file or open an existing one. You
can create a new M-file by selecting “File/New/M-file” from the desktop menu or by clicking the toolbar
icon. You can open an existing M-file file by selecting “File/Open” from the desktop menu or by
clicking the toolbar icon. The Edit Window is essentially a programming text editor, with the MATLAB
languages features highlighted in different colors. Comments in an M-file file appear in green, variables
and numbers appear in black, complete character strings appear in magenta, incomplete character strings
appear in red, and language keywords appear in blue. After an M-file is saved, it may be executed by
typing its name in the Command Window.
Course Code: 20EC0454 R20
A Figure Window is used to display MATLAB graphics. A figure can be a twoor three-dimensional
plot of data, an image, or a graphical user interface (GUI).
Course Code: 20EC0454 R20
b List the different ways that you can get help in MATLAB. write brief note on MATLAB help
system.
There are three ways to get help in MATLAB. The preferred method is to use the Help Browser. The
Help Browser can be started by selecting the icon from the desktop toolbar or by typing helpdesk or
helpwin in the Command Window. A user can get help by browsing the MATLAB documentation, or he
or she can search for the details of a particular command. The Help Browser is shown in Figure 1
There are also two command-line–oriented ways to get help. The first way is to type help or help
followed by a function name in the Command Window. If you just type help, MATLAB will display a
list of possible help topics in the Command Window. If a specific function or a toolbox name is
included, help will be provided for that particular function or toolbox.
The second way to get help is the lookfor command. The lookfor command differs from the help
command in that the help command searches for an exact function name match, while the
Course Code: 20EC0454 R20
lookforcommand searches the quick summary information in each function for a match. This makes
lookfor slower than help, but it improves the chances of getting back useful information. For example,
suppose that you were looking for a function to take the inverse of a matrix. Since MATLAB does not
have a function named inverse, the command “help inverse” will produce nothing. On the other hand, the
command “lookfor inverse” will produce the following results:
This same allocation scheme applies to arrays with more than two dimensions. The first array
subscript is incremented most rapidly, the second subscript is incremented less rapidly, and so on, and
the last subscript in incremented most slowly. For example, in a array, the elements would be
allocated in the following order: (1,1,1), (2,1,1), (1,2,1), (2,2,1), (1,1,2), (2,1,2), (1,2,2), (2,2,2).
The MATLAB basic xy plotting function is plot(x,y). If x and y are vectors, a single curve is plotted
Course Code: 20EC0454 R20
with the x values on the abscissa and the y values on the ordinate. The xlabel and ylabel commands put
labels on the abscissa and the ordinate, respectively. The syntax is xlabel(‘text’), where text is the text of
the label.
The syntax for ylabel is the same. The title command puts a title at the top of the plot. Its syntax is
title(‘text’), where text is the title’s text. The plot(x,y) function in MATLAB automatically selects a tick-
mark spacing for each axis and places appropriate tick labels. This feature is called autoscaling.
MATLAB also chooses limits for the x and y axes. The order of the xlabel, ylabel, and title commands
does not matter, but we must place them after the plot command, either on separate lines using ellipses
or on the same line separated by commas.
Example for plot(x,y):
let us plot the function y = 5sin x for 0 ≤ x ≤ 7. We choose to use an increment of 0.01 to generate a
large number of x values in order to produce a smooth curve. The function plot(x,y) generates a plot with
the x values on the horizontal axis (the abscissa) and the y values on the vertical axis (the ordinate). The
session is
>>x = 0:0.01:7;
>>y = 3*cos(2*x);
>>plot(x,y), xlabel(‘x’), ylabel(‘y’)
The plot appears on the screen in a graphics window, as shown in Figure 1.3–1.
MATLAB has a “smart” command for plotting functions. The fplot command automatically analyzes the
function to be plotted and decides how many plotting points to use so that the plot will show all the
features of the function. Its syntax is fplot(function, [xmin xmax]), where function is a function handle to
the function to be plotted and [xmin xmax] specifies the minimum and maximum values of the
independent variable. The range of the dependent variable can also be specified. In this case the syntax is
fplot(function, [xmin xmax ymin ymax]).
For example, the session
>>f = @(x) (cos(tan(x)) - tan(sin(x)));
>>fplot(f,[1 2])
Course Code: 20EC0454 R20
MATLAB plotting commands are listed in the table along with the description.
A MATLAB function can have any number of arguments, and not all arguments need to be present each
Course Code: 20EC0454 R20
time the function is called. Function nargin is used to determine the number of input arguments actually
present when a function is called, and function nargout is used to determine the number of output
arguments actually present when a function is called.
Script file Function file
Script file are saved with the extension .m (that is Function file are saved with the extension .m
why they are sometimes called M-files). (that is why they are sometimes called M-files).
script file has no input arguments and returns no function can have any number of arguments, and
results, but script files can communicate with not all arguments need to be present each time the
other script files through the data left behind in function is called.
the workspace.
The first executable line in a script file is The first executable line in a function file is (must
initialization of variables. be) the function definition line.
The variables in a script file are recognized in the The variables in a function file are local. This
Command Window. means that the variables are defined and
recognized only inside the function file.
Script files can use variables that have been function runs in its own independent workspace.
defined in the workspace. It receives input data through an input argument
list and returns results to the caller through an
output argument list.
Script files contain a sequence of MATLAB Script files contain a sequence of MATLAB
commands (statements). commands (statements).
Scipt files can accept data through initialization Function files can accept data through input
or input command and display output data arguments and can return data through output
through disp or output commands arguments.
Script file can be saved with any name with When a function file is saved, the name of the file
extension .m should be the same as the name of the function
Script files are similar to main program in C, sunction files are similar to subroutines in Basic
FORTRAN . and Fortran, procedures in Pascal, and functions
in C
The global command must appear before the Local variable can appear anywhere in the
variable is used. It is recommended to enter the program.
global command at the top of the file.
The variable can be assigned, or reassigned, a
value in any of the locations in which it is
declared common.
The use of long descriptive names (or all capital The use of small letters and short names are
letters) is recommended for global variables in recommended for local variables.
order to distinguish them from regular variable
UNIT - II
ARRAYS
What is an array? Write short note on one dimensional and two-dimensional array and give
an example for each.
Array:The fundamental unit of data in any MATLAB program is the array. An array is a
collection of data values organized into rows and columns, and known by a single name as
shown in fig.1.
Three things need to be specified to declare an array in most of the programming languages:
1) the array name
2) the type of data to be stored in array elements
3) the subscript range
Individual data values within an array are accessed by including the name of the array followed by
subscripts in parentheses that identify the row and column of the particular value. Even scalars are
treated as arrays by MATLAB—they are simply arrays with only one row and one column. Arrays
can be classified as either vectors or matrices. The term “vector” is usually used to describe an array
with only one dimension, while the term “matrix” is usually used to describe an array with two or
more dimensions. In this text, we will use the term “vector” when discussing one-dimensional arrays,
and the term “matrix” when discussing arrays with two or more dimensions. If a particular discussion
applies to both types of arrays, we will use the generic term “array”. The size of an array is specified
1 a by the number of rows and the number of columns in the array, with the number of rows mentioned
first. The total number of elements in the array will be the product of the number of rows and the
number of columns. For example, the sizes of the following arrays are shown in Table 1
Fig.1 An array is a collection of data values organized into rows and columns
Course Code: 20EC0454 R20
Table 1
One dimensional arrays can be visualized as a series of values laid out in a row or column, with a
single subscript used to select the individual array elements (Figure 2a). Such arrays are useful to
describe data that is a function of one independent variable, such as a series of temperature
measurements made at fixed intervals of time.
Some types of data are functions of more than one independent variable. For example, we might
wish to measure the temperature at five different locations at four different times. In this case, our
20 measurements could logically be grouped into five different columns of four measurements
each, with a separate column for each location (Figure 2b). e.g a is a one dimensional array with
size 1x2
𝑎 = [−4 ]
3
In this case, we will use two subscripts to access a given element in the array—the first one to
select the row and the second one to select the column. Such arrays are called two-dimensional
arrays. The number of elements in a two-dimensional array will be the product of the number of
rows and the number of columns in the array
A two-dimensional array with m rows and n columns will contain m x n elements, and these
elements will occupy m x n successive locations in the computer’s memory. e.g. b is a two
dimensional array with size 2x2.
−4 5
𝑏 =[ ]
3 2
Ais a 3-by-3 array, that is, its row dimension is 3 and its column dimension is 3.
To add a third dimension to A,
A(:,:,2) = [1 0 4; 3 5 6; 9 8 7]
A(:,:,2) =
1 0 4
3 5 6
9 8 7
We can continue to add rows, columns, or pages to the array using similar
Course Code: 20EC0454 R20
assignment statements.
You can use MATLAB functions such as randn, ones, and zeros to generate
multidimensional arrays in the same way you use them for two-dimensional
arrays. Each argument you supply represents the size of the corresponding
dimension in the resulting array. For example, to create a 4-by-3-by-2 array of
normally distributed random numbers.
B = randn(4,3,2)
To generate an array filled with a single constant value, use
the repmat function. repmat replicates an array (in this case, a 1-by-1 array)
through a vector of array dimensions.
B = repmat(5,[3 4 2])
B(:,:,1) =
5 5 5 5
5 5 5 5
5 5 5 5
B(:,:,2) =
5 5 5 5
5 5 5 5
5 5 5 5
Note Any dimension of an array can have size zero, making it a form of empty array
For example, 10-by-0-by-20 is a valid size for a multidimensional array.
B(:,:,1) =
2 8
0 5
B(:,:,2) =
1 3
7 9
The cat function accepts any combination of existing and new data. In addition,
you can nest calls to cat. The lines below, for example, create a four-dimensional
array.
A = cat(3,[9 2; 6 5],[7 1; 8 4])
B = cat(3,[3 5; 0 1],[5 6; 2 1])
D = cat(4,A,B,cat(3,[1 2; 3 4],[4 3;2 1]))
Course Code: 20EC0454 R20
cat automatically adds subscripts of 1 between dimensions, if necessary. For
example, to create a 2-by-2-by-1-by-2 array, enter
C = cat(4,[1 2; 4 5],[7 8; 3 2])
In the previous case, cat inserts as many singleton dimensions as needed to create
a four-dimensional array whose last dimension is not a singleton dimension. If
the dim argument had been 5, the previous statement would have produced a 2-by-
2-by-1-by-1-by-2 array. This adds additional 1s to indexing expressions for the
array. To access the value 8 in the four-dimensional case, use
C(1,2,1,2)
Storing of Multidimensional Arrays
MATLAB always allocates array elements in column major order. The first array subscript is
incremented most rapidly, the second subscript is incremented less rapidly, and so on, and the last
subscript in incremented most slowly. For example, in a 2x2x2 array, the elements would be allocated
in the following order: (1,1,1), (2,1,1), (1,2,1), (2,2,1), (1,1,2), (2,1,2), (1,2,2), (2,2,2).
Fig: a) data values for array a b) Layout of values in memory for array a.
The coefficients an, an-1,… ............. a1 , a0 are real numbers, and n which is a nonnegative integer, is the
degree, or order, of the polynomial.
5 a
Polynomial Operations:
1) Find value of polynomial
The value of a polynomial at a point x can be calculated with the function polyval that has the form
x can also be a vector or a matrix. In such a case the polynomial is calculated for each element
(element-by-element), and the answer is a vector, or a matrix, with the corresponding values of the
polynomial. For example : f(x) = x2 - 2 x – 3 , The value of f(1) is -4. MatLab program
>>p = [1 -2 -3]
>>polyval(p,1)
Ans =
-4
2) Root of the polynomial:The roots of a polynomial are the values of the argument for
which the value of the polynomial is equal to zero. MATLAB has a function, called roots,
that determines the root, or roots, of a polynomial. The form of the function is:
Course Code: 20EC0454 R20
3) Find the co-efficients of Polynomial: When the roots of a polynomial are known, the
poly command can be used for determining the coefficients of the polynomial. The form of
the poly command is
For example : f(x) = x2 - 2 x – 3 , The value of f(1) is -4. MatLab program
>> r = [-1 3]
>> p = poly(r)
Ans =
P= 1 -2 3
4) Addition: Two polynomials can be added (or subtracted) by adding (subtracting) the vectors
of the coefficients. If the polynomials are not of the same order (which means that the vectors
of the coefficients are not of the same length), the shorter vector has to be modified to be of
the same length as the longer vector by adding zeros (called padding) in front. For example,
the polynomials f1(x)= 3 x6 +15 x5 - 10 x3 -3 x2 +15x - 40 and f1(x)= 3 x3 - 2x - 6 can be
added by:
5)
Course Code: 20EC0454 R20
6)
7)
Define Empty array with 3 examples.
Empty Array: Empty array is used to create an empty array which means there is no row and no
column. For creating empty array use brackets [] symbol.
e.g. A= []
then this expression creates an empty array, which contains no rows and no columns. (Note that this
is not the same as an array containing zeros.
Empty array are used in structured array. In the structure array all of the fields of a structure are
created for each array element whenever that element is defined, even if they are not initialized. The
uninitialized fields will contain empty arrays, which can be initialized with assignment statements at a
later time. For example, suppose that we add some exam scores to Jane Q Public’s record. This field
b will be initialized for student(2) and will be an empty array for all other students until appropriate
assignment statements have been issued. For example
» student(2).
ans =
name : 'Jane Q. Public'
addr1: []
city : []
state : []
zip: []
student is now a 1x2 array.
Describe about MATLAB array and discuss about the following functions with examples
used in MATLAB program: (i) Zeros ( ). (ii) Ones ( ). (iii) Eye ( ).
The fundamental unit of data in any MATLAB program is the array. An array is a collection
of data values organized into rows and columns, and known by a single name as shown in
fig.1.
Individual data values within an array are accessed by including the name of the array followed by
subscripts in parentheses that identify the row and column of the particular value. Even scalars are
treated as arrays by MATLAB—they are simply arrays with only one row and one column. Arrays
6 can be classified as either vectors or matrices. The term “vector” is usually used to describe an array
with only one dimension, while the term “matrix” is usually used to describe an array with two or
more dimensions. In this text, we will use the term “vector” when discussing one-dimensional arrays,
and the term “matrix” when discussing arrays with two or more dimensions.
If a particular discussion applies to both types of arrays, we will use the generic term “array”. The
size of an array is specified by the number of rows and the number of columns in the array, with the
number of rows mentioned first. The total number of elements in the array will be the product of the
number of rows and the number of columns. For example, the sizes of the following arrays are shown
in Table 1
Course Code: 20EC0454 R20
Fig.1 An array is a collection of data values organized into rows and columns
Table 1
Zeros function:the function zeros can be used to create an all-zero array of any desired size. There
are several forms of the zeros function. If the function has a single scalar argument, it will produce
a square array using the single argument as both the number of rows and the number of columns. If
the function has two scalar arguments, the first argument will be the number of rows, and the
second argument will be the number of columns. Since the size function returns two values
containing the number of rows and columns in an array, it can be combined with the zeros function
to generate an array of zeros that is the same size as another array. Some examples using the zeros
function follow:
a = zeros(2);
b = zeros(2,3);
d = zeros(size(c));
These statements generate the following arrays:
a=[0 0] b=[0 0 0]
0 0 0 0 0
d = [0 0]
0 0
Ones Function: the ones function can be used to generate arrays containing all ones. ones(m,n)
commands create a matrix with m rows and n columns in which all elements are the numbers 1.
b = ones(2,3)
1 1 1
b= [ ]
1 1 1
Eye Function:. The eye(n) command creates a square matrix with n rows and n columns in which
the diagonal elements are equal to 1 and the rest of the elements are 0. This matrix is called the
identity matrix. the eye function can be used to generate arrays containing identity matrices, in
which all on-diagonal elements are one, while all off-diagonal elements are zero.
C = eye(3)
1 0 0
C= [0 1 0]
0 0 1
Distinguish between array multiplication and matrix multiplication with an example.
Matrix Multiplication: general result for matrix multiplication as follows:
Suppose A has dimension m x p and B has dimension p x q. If C is the product AB, then C has
7 a dimension m x q and its elements are given by
𝑛 Eq(1)
𝑐(𝑖, 𝑗) = ∑ 𝑎(𝑖, 𝑘)𝑏(𝑗, 𝑘)
𝑘=1
Course Code: 20EC0454 R20
Explain about the functions to sort, rotate, permute, reshape, shift array contents and circshift
array contents.
Function to sort:
• % Get the length of the array to sort
nvals = size(a,2);
% Sort the input array
for ii = 1:nvals-1
% Find the minimum value in a(ii) through a(n)
iptr = ii;
for jj = ii+1:nvals
if a(jj) < a(iptr)
iptr = jj;
end
end
% iptr now points to the minimum value, so swap a(iptr) % with a(ii)
if ii ~= iptr
temp = a(ii);
a(ii) = a(iptr);
a(iptr) = temp;
end
end
% Pass data back to caller
out = a;
Function to rotate:
9
Function to permute:This function willrearrange the dimensions of a multidimensional array
Syntax
• B = permute(A,order)
Description
B = permute(A,order) rearranges the dimensions of A so that they are in the order specified
by the vector order. B has the same values of A but the order of the subscripts needed to
access any particular element is rearranged as specified by order. All the elements
of order must be unique.
Remarks
permute and ipermute are a generalization of transpose (.') for multidimensional arrays.
Examples
Given any matrix A, the statement
• permute(A,[2 1])
is the same as A'.
For example:
A = [1 2; 3 4]; permute(A,[2 1])
ans
=13
24
The following code permutes a three-dimensional array:
X = rand(12,13,14);
Y = permute(X,[2 3 1]);
size(Y)
ans
= 13 14 12
Function to reshape:
Course Code: 20EC0454 R20
Function to shift array contents:
What is structure? How does it differ from ordinary arrays and cell arrays?
Structure arrays are composed of structures. This class of arrays enables you to store dissimilar arrays
together. The elements in structures are accessed using named fields. This feature distinguishes them
from cell arrays, which are accessed using the standard array indexing operations. Structure arrays are
used in this text only in this section. Some MATLAB toolboxes do use structure arrays.
Suppose you want to create a database of students in a course, and you want to include each student’s
name, Social Security number, email address, and test scores. Figure 2.7–1 shows a diagram of this
data structure. Each type of data (name, Social Security number, and so on) is a field, and its name is
the field name. Thus our database has four fields. The first three fields each contain a text string,
while the last field (the test scores) contains a vector having numerical elements. A structure consists
of all this information for a single student. A structure array is an array of such structures for different
students. The array shown in Figure 1 has two structures arranged in one row and two columns
10 a
Creating Structures :We can create a structure array by using assignment statements or by using the
struct function. The following example uses assignment statements to build a structure. Structure
Course Code: 20EC0454 R20
arrays use the dot notation (.) to specify and to access the elds. We can type the commands either in
the interactive mode or in a script le.
Example: Create a structure array to contain the following types of student data:
■ Student name.
■ Social Security number.
■ Email address.
■ Test scores.
Enter the data shown in Figure 1 into the database.
How structure arrays differs from an ordinary array and cell arrays: Structures differ from
ordinary arrays and cell arrays in that ordinary arrays and cell array elements are addressed by
subscript, but structure elements are addressed by name.
UNIT – III
FUNCTIONS AND FILES
What are functions? what its types. (Built-in and User Defined )
Functions:Functions are perhaps the most important tool for programming. They allow the
programmer to define a specific action that (usually) takes in some data, does some
processing, and returns a result, much like most math functions. Yet, no matter what the
purpose of a function is, the "syntax" for defining and using a function is always the same.
There are mainly two types of Functions in MATLAB.
1) Built-in Function: Built-in functions are those that come with MATLAB or are part of
an add-on product. The user typically don’t have source code for built-in functions
and must treat them simply as black boxes. Built-in function are embedded in
language. They are provided by compiler. Many functions are programmed inside
MATLAB as built-in functions, and can be used in mathematical expressions simply
by typing their name with an argument; examples are sin(x), cos(x), sqrt(x), and
exp(x). MATLAB has a plethora of built-in functions for mathematical and scientific
computations.
2) User defined Function: User defined functions are provided by user or brought from
2 a an external library. The M- file of user defined function is a function file. Unlike a
script file, all the variables in a function file are local variables, which means their
values are available only within the function. Function les are useful when you need to
repeat a set of commands several times. They are the building blocks of larger
programs. To create a function le, open the Editor /Debugger. The first line in a
function file must begin with a function definition line that has a list of inputs and
outputs. This line distinguishes a function M- file from a script M- file.
Its syntax is as follows:
function [outarg1, outarg2, ...] = function_name(inarg1, inarg2, ...)
% H1 comment line
% Other comment lines
...
(Executable code)
...
(return)
(end)
Course Code: 20EC0454 R20
Importing Spreadsheet Files Some spreadsheet programs store data in the .wk1 format. You can use
the command M = wk1read(‘filename’) to import these data into MATLAB and store them in the
matrix M. The command A = xlsread(‘filename’) imports the Microsoft Excel workbook le
filename.xls into the array A. The command [A, B] = xlsread(‘filename’) imports all numeric data into
the array A and all text data into the cell array B.
Exporting ASCII Data Files: One might want to export a MATLAB matrix as an ASCII data file
where the rows and columns are represented as space-delimited, numeric values. To export a
MATLAB matrix as a delimited ASCII data file, one can use either the save command, specifying the -
ASCII qualifier , or the dlmwrite function. The save command is easy to use; however, the dlmwrite
function provides greater exibility , allowing you to specify any character as a delimiter and to export
subsets of an array by specifying a range of values. Suppose you have created the array A = [1 2 3 4; 5
6 7 8] in MATLAB. To export the array using the save command, type the following in the Command
window.
>>save my_data.out A -ASCII
By default, save uses spaces as delimiters, but you can use tabs instead of spaces by specifying the -tab
qualifier .
What are the user defined functions? Write MATLAB program to sort vector v = [23 45 12 9 5 0 19
17] using MATLAB commands.
A user-defined function is a MATLAB program that is created by the user, saved as a function
file, and then can be used like a built-in function. The function can be a simple, single
mathematical expression or a complicated and involved series of calculations. In many cases it
is actually a subprogram within a computer program. The main feature of a function file is that
it has an input and an output. This means that the calculations in the function file are carried
out using the input data, and the results of the calculations are transferred out of the function
file by the output. The input and the output can be one or several variables, and each can be a
scalar, vector, or an array of any size. Schematically, a function file can be illustrated by:
Input code written in function file ‘compute_area.m’ is as follows for the computation
of area of a circle.
function Area = compute_area (rad)
Area = pi*(rad.^2)
Course Code: 20EC0454 R20
Mention the syntax of function statement and create a user defined function to return the maximum
number when three numbers are given as arguments.
Syntax to create a user-defined function:
function [o1, o2, o3…, on] = func_name (i1, i2, i3, …,im)
Description of the syntax:
Input code written in function file ‘max_num.m’ is as follows for the computation of
maximum number.
n1=input('Please enter a number:');
n2=input('Please enter a number:');
n3=input('Please enter a number:');
function max = max_num(n1,n2,n3)
max=n1;
if n2>max
4 max=n2;
end
if n3>max
max=n3;
end
max_num(n1,n2,n3);
fprintf('The maximum number is:%d\n ',max)
end
Explain any 3 complex number handling functions in MATLAB.
Complex numbers are numbers with both a real and an imaginary component. A complex number has
the general form c = a + bi
MATLAB includes many functions that support complex calculations. These functions fall into three
general categories:
1. Type conversion functions: These functions convert data from the complex data type to the real
(double) data type. Function real converts the real part of a complex number into the double data type
and throws away the imaginary part of the complex number. Function imag converts the imaginary part
of a complex number into a real number.
2. Absolute value and angle functions: These functions convert a complex number to its polar
b representation. Function abs(c) calculates the absolute value of a complex number using the
equation
abs(c) =√𝑎2 + 𝑏2
where c = a + bi
Function angle(c) calculates the angle of a complex number using the equation
angle(c) = atan2(imag(c), real(c))
producing an answer in the range -π ≤ θ ≤π
3. Mathematical functions:Most elementary mathematical functions are defined for complex values.
These functions include exponential functions, logarithms, trigonometric functions, and square roots.
The functions sin, cos, log, sqrt, and so forth will work as well with complex data as they will with real
Course Code: 20EC0454 R20
data.
Explain briefly about methods for calling functions.
There are four ways to invoke, or “call,” a function into action:
1. As a character string identifying the appropriate function M-file
2. As a function handle
3. As an “inline” function object
4. As a string expression
Examples of these ways follow for the fzero function used with the user-defined function fun1, which
computes y = x2 - 4.
1. As a character string identifying the appropriate function M-file, which is
function y = fun1(x)
y = x.^2-4;
a The function may be called as follows, to compute the zero over the range 0 ≤ x ≤3:
>>x = fzero(‘fun1’,[0, 3])
2. As a function handle to an existing function M-file:
>>x = fzero(@fun1,[0, 3])
3. As an “inline” function object:
>>fun1 = ‘x.^2-4’;
>>fun_inline = inline(fun1);
>>x = fzero(fun_inline,[0, 3])
5 4. As a string expression:
>>fun1 = ‘x.^2-4’;
>>x = fzero(fun1,[0, 3]) or as
>>x = fzero(‘x.^2-4’,[0, 3])
Write MATLAB function to compute function circle which computes the area A and circumference C
of a circle, given its radius as an input argument.
First we will write following function for the computation of the area A and circumference of a
circle
function [area,circum] = circle(r)
% [area, circum] = circle(r) returns the area and circumference of a circle with radius r.
area = pi*r^2;
circum = 2*pi*r;
b the function circle® will m=be called in the main program. For example
r = 7;
[area,circum] = circle(r);
% call our circle function.
disp([‘The area of a circle having…
radius ‘ num2str(r) ‘ is ‘… num2str(area)]);
Explain different types of user defined functions which are created in MATLAB.
1) Primary function: The primary function is the first function in an M-file and typically
contains the main program. Following the primary function in the same file can be any
number of subfunctions, which can serve as subroutines to the primary function.
Usually the primary function is the only function in an M-file that you can call from
the MA TLAB command line or from another M- file function. We invoke this
function by using the name of the M- file in which it is defined. We normally use the
same name for the function and its file, but if the function name differs from the file
6 a name,we must use the file name to invoke the function.
2) Anonymous functions: Anonymous functions enable us to create a simple function
without needing to create an M- file for it. We can construct an anonymous function
either at the MATLAB command line or from within another function or script. Thus,
anonymous functions provide a quick way of making a function from any MATLAB
expression without the need to create, name, and save a file.
3) Subfunctions :Subfunctions are placed in the primary function and are called by the
primary function. We can use multiple functions within a single primary function M-
file.
Course Code: 20EC0454 R20
4) Nested functions: Nested functions are functions defined within another function.
They can help to improve the readability of your program and also give you more
flexible access to variables in the M- file. The difference between nested functions and
subfunctions is that subfunctions normally cannot be accessed outside of their primary
function file.
5) Overloaded functions :Overloaded functions are functions that respond differently to
different types of input arguments. They are similar to overloaded functions in any
object-oriented language. For example, an overloaded function can be created to treat
integer inputs differently than inputs of class double.
6) Private functions :Private functions enable you to restrict access to a function. They
can be called only from an M-file function in the parent directory.
In this window, select Create vectors from each column using column names. Make sure the desired
variables are checked, as shown in Fig. 5, then click Finish. The following message should appear in
the command window: >>Import Wizard created variables in the current workspace. If "whos" is
typed, the assigned variables in Excel are now in the MATLAB workspace, as shown in Fig. 6
Open the To Workspace block, and in the Variable Name field, type in "y" (no quotes). This will be the
name of the output variable. Now select Array from the pull down menu. Leave the default values for
the remaining fields. The To Workspace block will allow for the transfer data from the Simulink model
to the MATLAB workspace, where further manipulation of the data for export to Excel can be
performed. When the simulation for the model above is run, MATLAB will create an output array
assigned to the variable y, and a time array assigned to the default variable tout. Create a matrix
combining these two arrays, with tout as the first column and y as the second column. Once this has
been done, one simple command will create an Excel file. After running the simulation, go to the
MATLAB workspace. At the command prompt type in the following commands:
>>A = [tout, y];
>>save filename.xls A –ascii
A file named filename.xls will be written in the current working directory. Open Excel and choose File
→ Open, go to the working directory and select filename.xls → Open, and a window will appear as
shown in Fig. 2.
Course Code: 20EC0454 R20
Follow the instructions in the window to set the column break, and select Next → Finish. The data will
be brought into Excel in two columns. The first column will be the time vector and the second column
will be the values of y.
Write short note on Minimizing a Function of One Variable.
The fminbnd function finds the minimum of a function of a single variable, which is denoted by x. Its
basic syntax is
fminbnd(@function, x1, x2)
where @function is a function handle.
The fminbnd function returns a value of x that minimizes the function in the interval x1 ≤ x ≤ x2. For
example, fminbnd(@cos,0,4) returns the value x = 3.1416. However, to use this function to find the
minimum of more-complicated functions, it is more convenient to de ne the function in a function le.
For example, if y = 1 – xe-x , define the following function file:
function y = f2(x)
y = 1-x.*exp(-x);
To find the value of x that gives a minimum of y for 0 ≤ x ≤ 5, type x = fminbnd(@f2,0,5). The answer
is x = 1. To find the minimum value of y, type y = f2(x). The result is y = 0.6321.
8 a Whenever we use a minimization technique, we should check that the solution is a true minimum. For
example, consider the polynomial y = 0.025x5 – 0.0625x4 - 0.333x3 + x2
Its plot is shown in Figure 3.2–2. The function has two minimum points in the interval -1 ≤ x ≤ 4. The
minimum near x = 3 is called a relative or local minimum because it forms a valley whose lowest point
is higher than the minimum at x = 0. The minimum at x = 0 is the true minimum and is also called the
global minimum. First create the function file function
y = f3(x)
y = polyva1([0.025, -0.0625, -0.333, 1, 0, 0], x);
To specify the interval -1 ≤ x ≤ 4, type x = fminbnd(@f3, -1, 4). MATLAB gives the answer x =
2.0438e-006, which is essentially 0, the true minimum point. If we specify the interval 0.1 ≤ x ≤ 2.5,
MATLAB gives the answer x = 0.1001, which corresponds to the minimum value of y on the interval
0.1 ≤ x ≤ 2.5. Thus we will miss the true minimum point if our speci- ed interval does not include it.
Also fminbnd can give misleading answers. If we specify the interval -1 ≤ x ≤ 4, MATLAB (R2009 b)
gives the answer x = 2.8236, which corresponds to the “valley” shown in the plot, but which is not the
Course Code: 20EC0454 R20
We will now break each of the above major sections into smaller, more detailed pieces.
There are four possible ways to calculate the function f(x,y)
depending upon the values of x and y, so it is logical to implement this algorithm with a four-
branched if construct. The resulting pseudocode is
Algorithm
Read x and y
if x ≥ 0 and y ≥ 0
fun <-x + y^ 2
else
end
%This program solves the function f(x, y) for a user-specified x and y, where %f(x,y) is
defined as:
fun = x + y;
fun = x + y^ 2 ;
fun = x^2 + y
else
Course Code: 20EC0454 R20
fun = x^2 + y^2
end
Next, we must test the program using real input data. Since there are four possible paths
through the program, we must test all four paths before can be certain that the program is
working properly. To test all four possible paths, we will execute the program with the four
sets of input values (x,y) = (2, 3), (2,-3), (-2, 3), and (-2,-3). Calculating by hand, we see the
f(2,3) = 2+3 = 5
f(2,-3) = 2+(-3) 2 = 11
f(-2,3) = (-2) 2 + 3 = 7
If this program is compiled, and then run four times with the above values, the results are:
>> funxy
» funxy
» funxy
>>funxy
The program gives the correct answers for our test values in all four possible cases.
Course Code: 20EC0454 R20
Write short note on Minimizing a Function of several Variable.
Minimizing a Function of Several Variables To find the minimum of a function of more than one
variable, use the fminsearch function. Its basic syntax is
fminsearch(@function, x0)
where @function is a function handle. The vector x0 is a guess that must be supplied by the user. For
example, to use the function , first define it in an M-file, using the vector x whose elements are
x(1) = x and x(2) = y.
function f = f4(x)
f = x(1).*exp(-x(1).^2-x(2).^2);
Suppose we guess that the minimum is near x = y= 0. The session is
>>fminsearch(@f4, [0, 0])
ans =
- 0.7071 0.000
Thus the minimum occurs at x = - 0.7071, y = 0. The fminsearch function can often handle
discontinuities, particularly if they do not occur near the solution. The fminsearch function might give
a local solutions only, and it minimizes over the real numbers only; that is, x must consist of real
variables only, and the function must return real numbers only. When x has complex values, they must
be split into real and imaginary parts. Table :1 summarizes the basic syntax of the fminbnd,
fminsearch, and fzero commands. These functions have extended syntax not described here. With these
forms you can specify the accuracy required for the solution as well as the number of steps to use
before stopping. Use the help facility to find out more about these functions.
9 Table :1 Minimization and root- finding functions F
fminbnd(@function,x1,x2) Returns a value of x in the interval x1 ≤ x ≤ x2
that corresponds to a minimum of the single-variable
function described by the handle @function.
fminsearch(@function,x0) Uses the starting vector x0 to find a minimum of the
multivariable function described by the handle @function.
fzero(@function,x0) Uses the starting value x0 to find a zero of the
single-variable function described by the handle @function.
Write a function that accepts temperature in degrees Fahrenheit (°F) and computes the
corresponding value in degrees Celsius (°C). The relation
between the two is T °C = 5/9 * (T °F - 32)
function [v_degcelsius] = tempconversion(v_Far)
v_degcelsius = 5/9 * (v_Far – 32)
end
b
Main Program
c = tempconversion(97)
Ans =
36.1111
e.g.
>>fix(12/5)
Ans =
2
floor(x) : Round toward the nearest integer.
Dcscíiptio⭲ B = rlooí (A) ío"⭲ds tkc clcmc⭲ts or A to tkc ⭲caícst i⭲tcgcís lcss tka⭲ oí cq"al to
A. Foí complcx A, tkc imagi⭲aíQ a⭲d ícal paíts aíc ío"⭲dcd i⭲dcpc⭲dc⭲tlQ.
e.g.
>>floor(-9/4)
Ans =
-3
sign(x) : Signum function: +1 if x > 0;
0 if x = 0;
-1 if x < 0.
e.g.
>>sign(5)
Ans =
3
Let x = -5-8i and y=10-5i. Use MATLAB to compute the following expressions. Hand-check
the answers.
i. The magnitude and angle of xy.
ii. The magnitude and angle of x/y
Complex numbers are numbers with both a real and an imaginary component. A complex number has
the general form c = a + bi
MATLAB includes many functions that support complex calculations. These functions fall into three
general categories:
1. Type conversion functions: These functions convert data from the complex data type to the real
(double) data type. Function real converts the real part of a complex number into the double data type
and throws away the imaginary part of the complex number. Function imag converts the imaginary part
of a complex number into a real number.
2. Absolute value and angle functions: These functions convert a complex number to its polar
representation. Function abs(c) calculates the absolute value of a complex number using the equation
abs(c) =√𝑎2 + 𝑏2
where c = a + bi
Function angle(c) calculates the angle of a complex number using the equation
b angle(c) = atan(imag(c), real(c))
producing an answer in the range -π ≤ θ ≤π
The MATLAB abs(x) and angle(x) functions calculate the magnitude M and angle θ of the complex
number x. The functions real(x) and imag(x) return the real and imaginary parts of x. The magnitude of
the product z of two complex numbers x and y is equal to the product of their magnitudes: The angle of
the product is equal to the sum of the angles:
These facts |𝑧| = |𝑥||𝑦| 𝑎𝑛𝑑 ∠𝑧 = ∠𝑥 + ∠𝑦 are demonstrated below.
mag_division =
0.8438
>> angle_division=angle(x/y)
angle_division =
-1.6657
To compute the given expression for given x = -5 – 8i and y = 10 – 5i
1) The magnitude and angle of xy
%Compute The magnitude and angle of xy
x = -5-8i ;
y=10-5i;
z1 = abs(x*y)
anglez1 = angle(x*y)
Result
>> complex
z1 =
105.4751
anglez1 =
-2.5930
Hand calculation:
abs(x) =9.4340
abs(y) = 11.1803
angle(x) = -2.1294
angle(y) = -0.4636
Magnitude of x*y = abs(x)* abs(y)
= 9.4340 * 11.1803
= 105.4750
Angle of x/y = ∠𝒛 = ∠𝒙 + ∠𝑦
= 𝒂𝒏𝒈𝒍𝒆(𝒙) + 𝒂𝒏𝒈𝒍𝒆(𝒚)
= (−𝟐. 𝟏𝟐𝟗𝟒) + (−𝟎. 𝟒𝟔𝟑𝟔)
= −𝟐. 𝟓𝟗𝟑𝟎
2) The magnitude and angle of x/y
%Compute The magnitude and angle of x/y
>>x = -5-8i ;
>>y=10-5i;
>>z1 =abs(x/y)
>>anglez1 = angle(x/y)
Result
>> complex
z1 =
0.8438
anglez1 =
-1.6657
Course Code: 20EC0454 R20
Hand calculation:
abs(x) =9.4340
abs(y) = 11.1803
angle(x) = -2.1294
angle(y) = -0.4636
Magnitude of x/y = abs(x)/ abs(y)
= 9.4340/ 11.1803
= 0.8438
Angle of x/y = > ∠𝒛 = ∠𝒙 − ∠𝒚
= 𝒂𝒏𝒈𝒍𝒆(𝒙) − 𝒂𝒏𝒈𝒍𝒆(𝒚)
= (−𝟐. 𝟏𝟐𝟗𝟒) − (−𝟎. 𝟒𝟔𝟑𝟔)
= −𝟏. 𝟔𝟔𝟓𝟕
UNIT – IV
PROGRAMMING TECHNIQUES AND PLOTTING
2. Define the inputs required by the program and the outputs to be produced by the program.
The inputs to the program and the outputs to be produced by the program must be specified so that
the new program will properly fit into processing scheme.
3. Design the algorithm that you intend to implement in the program.
An algorithm is a step-by-step procedure for finding the solution to a problem. It is at this stage
in the process that top-down design techniques come into play. The designer looks for logical
divisions within the problem and divides it up into sub-tasks along those lines. This process is
called decomposition. If the sub-tasks are themselves large, the designer can break them up into
even smaller sub–sub-tasks. This process continues until the problem has been divided into
many small pieces, each of which does a simple, clearly understandable job. After the problem
has been decomposed into small pieces, each piece is further refined through a process called
stepwise refinement. In stepwise refinement, a designer starts with a general description of what
the piece of code should do and then defines the functions of the piece in greater and greater
detail until they are specific enough to be turned into MATLAB statements. Stepwise refinement
is usually done with pseudocode.
4. Turn the algorithm into MATLAB statements.
If the decomposition and refinement process was carried out properly, this step will be very
simple. All the programmer will have to do is to replace pseudocode with the corresponding
MATLAB statements on a one-for-one basis.
5. Test the resulting MATLAB program. In this step, the components of the program must first be
tested individually, if possible, and then the program as a whole must be tested. When testing a
program, we must verify that it works correctly for all legal input data sets. It is very common for a
program to be written, tested with some standard data set, and released for use, only to find that it
produces the wrong answers (or crashes) with a different input data set. If the algorithm
implemented in a program includes different branches, we must test all of the possible branches to
confirm that the program operates correctly under every possible circumstance.
The first stage of testing is sometimes called unit testing. During unit testing, the individual sub-
tasks of the program are tested separately to confirm that they work correctly. After the unit
testing is completed, the program goes through a series of builds during which the individual
sub-tasks are combined to produce the final program. Testing continues even after the program
is complete.
Once testing is done, then the program is ready to release.
Course Code: 20EC0454 R20
Lists the requirements essential to producing plots that communicate effectively.
The list of the requirements essential to producing plots that communicate effectively is as follows:
1. Each axis must be labeled with the name of the quantity being plotted and its units! If two or
more quantities having different units are plotted (such as when in a plot of both speed and
distance versus time), indicate the units in the axis label, if there is room, or in the legend or
labels for each curve.
2. Each axis should have regularly spaced tick marks at convenient intervals—not too sparse, but not too
dense—with a spacing that is easy to interpret and interpolate. For example, use 0.1, 0.2, and so on,
rather than 0.13, 0.26, and so on.
3. If you are plotting more than one curve or data set, label each on its plot, use different line types, or
use a legend to distinguish them.
b 4. If you are preparing multiple plots of a similar type or if the axes’ labels cannot convey enough
information, use a title.
5. If you are plotting measured data, plot each data point with a symbol such as a circle, square, or cross
(use the same symbol for every point in the same data set). If there are many data points, plot them using
the dot symbol.
6. Sometimes data symbols are connected by lines to help the viewer visualize the data, especially if
there are few data points. However, connecting the data points, especially with a solid line, might be
interpreted to imply knowledge of what occurs between the data points. Thus you should be careful to
prevent such misinterpretation.
7. If you are plotting points generated by evaluating a function (as opposed to measured data), do not use
a symbol to plot the points. Instead, be sure to generate many points, and connect the points with solid
lines.
Testing of the final alpha release by in-house personnel and by familiar and trusted outside users, who
often must sign a confidentiality agreement. This is the beta release phase, and there might be several
beta releases.
Course Code: 20EC0454 R20
List various relational operators available in MATLAB with detailed description.
MATLAB has six relational operators to make comparisons between arrays.
Note that the equal to operator consists of two = signs, not a single = sign as you might
expect. The single = sign is the assignment, or replacement, operator in MATLAB.
The result of a comparison using the relational operators is either 0 (if the comparison is
false) or 1 (if the comparison is true), and the result can be used as a variable.
Use of Relational Operator:
• When used to compare arrays, the relational operators compare the arrays on an
element-by-element basis. The arrays being compared must have the same dimension.
The only exception occurs when we compare an array to a scalar. . In that case all the
elements of the array are compared to the scalar.
• For example, suppose that x = [6,3,9] and y = [14,2,9].
>>z = (x < y)
b z=100
>>z = (x ~= y)
z=110
>>z = (x > 8)
z=001
• For example, with x = [6,3,9] and y = [14,2,9],
z = x(x < y)
• finds all the elements in x that are less than the corresponding elements in y.
• The arithmetic operators +, -, *, /, and \ have precedence over the relational operators.
• Thus the statement
z = 5 > 2 + 7 is equivalent to z = 5 >(2+7)
returns the result z = 0.
We can use parentheses to change the order of precedence;
for example,
z = (5 > 2) + 7 evaluates to z = 8.
The relational operators have equal precedence among themselves, and MATLAB evaluates
them in order from left to right.
Thus the statement
z = 5 > 3 ~= 1 is equivalent to z = (5 > 3) ~= 1
Both statements return the result z = 0.
With relational operators that consist of more than one character, such as == or >=, be careful
not to put a space between the characters.
Conditional Statements
If the expression is false, the computer skips the group.
The basic form of a conditional statement is: if statement
Examples:
if a < b else statement
if c >= 5
if a == b
elseif statement
if a ~= 0
if (d<h)&(x>7)
if (x~=13) | (y<0)
• Conditional statements can be a part of a program written in a script file or a user-defined function .
• As shown below, for every if statement there is an end statement. The if statement is commonly used
in three structures, if-end, if-else-end, and if-elseif-else-end.
Course Code: 20EC0454 R20
FOR LOOP:
The for loop is a loop that executes a block of statements a specified number of times. The for loop has
the form
for index = expr
...
... Body
...
end
where index is the loop variable (also known as the loop index) and expr is the loop control expression,
whose result is an array. The columns in the array produced by expr are stored one at a time in the
variable index and then the loop body is executed, so that the loop is executed once for each column in
the array produced by expr. The expression usually takes the form of a vector in shortcut notation
first:incr:last.
Example: The following statements form the 5-by-5 symmetric matrix A with (i, j) element i/j for j ≥ i.
n = 5;
A = eye(n);
for j=2:n
for i=1:j-1
A(i,j)=i/j;
A(j,i)=i/j;
end
end
2) Selection
The if statement evaluates a logical expression and executes a group of statements when the expression
is true. The optional elseif and else keywords provide for the execution of alternate groups of statement.
An end keyword, which matches the if, terminates the last group of statements. The groups of statement
are delineated by the four keywords--no braces or brackets are involved.
The general syntax of an if/elseif/else construct is:
if expression1
% Executed when expression1 is true
elseif expression2
% Executed when expression2 is true
End
Example 1:
if (i <= 10)
j = 0;
else
k = 0;
end
Example 2:
x = rand;
if x < 1/3
disp(‘x < 1/3’);
elseif x < 2/3
disp(‘1/3 <= x < 2/3’);
else
Course Code: 20EC0454 R20
A = eye(n);
for j=2:n
for i=1:j-1
A(i,j)=i/j;
A(j,i)=i/j;
end
end
function y = fun1(x)
y = x.^2-4;
The function may be called as follows, to compute the zero over the range 0 ≤ x≤ 3:
>>x = fzero(‘fun1’,[0, 3])
4. As a string expression:
>>fun1 = ‘x.^2-4’;
>>x = fzero(fun1,[0, 3])
or as
>>x = fzero(‘x.^2-4’,[0, 3])
Examples
Course Code: 20EC0454 R20
Polar Plot
where @function is a function handle. The fminbnd function returns a value of x that minimizes the
function in the interval x1≤ x ≤ x2.
For example, fminbnd(@cos,0,4) returns the value x = 3.1416. However, to use this function to find the
minimum of more-complicated functions, it is more convenient to de ne the function in a function file.
For example, if y = 1 – xe-x , define the following function file:
function y = f2(x)
y = 1-x.*exp(-x);
To find the value of x that gives a minimum of y for 0 ≤ x≤ 5, type x = fminbnd(@f2,0,5). The answer is
x = 1. To find the minimum value of y, type y = f2(x). The result is y = 0.6321.
Whenever we use a minimization technique, we should check that the solution is a true minimum. For
example, consider the polynomial y = 0.025x5 – 0.0625x4 – 0.333x3 + x2.
function y = f3(x)
y = polyva1([0.025, -0.0625, -0.333, 1, 0, 0], x);
To specify the interval -1≤ x ≤ 4, type x = fminbnd(@f3, -1, 4). MATLAB gives the answer x =
2.0438e-006, which is essentially 0, the true minimum point. If we specify the interval 0.1 ≤ x≤ 2.5,
MATLAB gives the answer x = 0.1001, which corresponds to the minimum value of y on the interval
0.1≤ x≤ 2.5. Thus we will miss the true minimum point if our specified interval does not include it.
Input code written in function file ‘compute_area.m’ is as follows for the computation of
area of a circle.
function Area = compute_area (rad)
Area = pi*(rad.^2)
compute_area (5)
[Passing the input argument as 5 to the compute_area function]
end
Output:
Ans = 78.5398
Note that the sqrt function returns the positive root only
Explain function discovery with its types.
Function discovery is the process of finding, or “discovering,” a function that can describe a particular
set of data. The following three function types can often describe physical phenomena.
1. The linear function: y(x) = mx+b. Note that y(0) = b.
2. The power function: y(x) = bxm. Note that y(0) = 0 if m ≥ 0, and y(0)= ∞ if m < 0.
3. The exponential function: y(x) = b(10)mx or its equivalent form y= bemx, where e is the base of the
9 natural logarithm (ln e 1). Note that y(0) = b for both forms.
function discovery is the technique for using data plots to obtain a mathematical function or
“mathematical model” that describes the process that generated the data.
Each function gives a straight line when plotted using a specific set of axes:
1. The linear function y= mx +b gives a straight line when plotted on rectilinear axes. Its slope is m and
its intercept is b.
2. The power function y = bxm gives a straight line when plotted on log-log axes.
3. The exponential function y=b(10)mx and its equivalent form y = bemx give a straight line when plotted
on a semilog plot whose y axis is logarithmic.
b We look for a straight line on the plot because it is relatively easy to recognize, and therefore we can
easily tell whether the function will fit the data well.
In function discovery applications, we use the log-log and semilog plots only to identify the function
type, but not to find the coefficients b and m. The reason is that it is difficult to interpolate on log
scales.We can find the values of b and m with the MATLAB poly t function. This function finds the
coefficients of a polynomial of specified degree n that best fits the data, in the so-called least-squares
sense. The syntax appears in command
P = poly t (x,y,n)
poly t commands fits a polynomial of degree n to data described by the vectors x and y, where x is the
independent variable. Returns a row vector p of length n +1 that contains the polynomial coefficients in
order of descending powers.
This polynomial has a different interpretation in each of the three cases:
■ The linear function: y= mx +b . In this case the variables w and z in the polynomial w = p1z+ p2 are the
original data variables x and y, and we can find the linear function that fits the data by typing
p = poly t(x,y,1).
The first element p1 of the vector p will be m, and the second element p2 will be b.
■ The power function: y = bxm. In this case log10 y =m log10 x + log10 b, which has the form w = p1z+ p2,
Course Code: 20EC0454 R20
where the polynomial variables w and z are related to the original data variables x and y by w= log10 y
and z = log10 x. Thus we can find the power function that fits the data by typing
p = poly t(log10(x), log10(y),1).
The first element p1 of the vector p will be m, and the second element p2 will be log10 b. We can find b
from b= 10𝑝2
■ The exponential function:y = b(10)mx. In this case log10 y = mx+ log10 b, which has the form w = p1z+
p2, where the polynomial variables w and z are related to the original data variables x and y by w= log10
y and z =x. Thus we can find the exponential function that fits the data by typing
p = poly t(x, log10(y),1).
The first element p1 of the vector p will be m, and the second element p2 will be log10 b. We can find b
from 10𝑝2 .
Explain plot commands (a) plot (x,y), (b) title( ), (c) xlabel( ) (d) ylabel( ) (e) legend ( ) in
MATLAB with an example.
Plot Commands
(a) Plot(x,y)= plot(x,y) command is used to plot the 2-Dimensional graph using data set. It
produces two vectors graph containing the x and y values to be plotted as y versus x.
E.g.
>>x =0:1:10
>>y=x.^2-10.x+15
>> plot(x,y)
When plot function executed, MATLAB opens a figure window and displays the plot in that
window as shown in fig.1
a b) title(): The title command add s a title at the top of the figure. The text written in between the
single quote will display as heading in the graph.
e.g. title(‘sinusoidal input signal’)
it will display sinusoidal input signal on the to of the graph as shown in fig.1
b
Three-Dimensional Line Plots
Lines in three-dimensional space can be plotted with the plot3 function. Its syntax is plot3(x,y,z).
For example, the following equations generate a three-dimensional curve as the parameter t is varied
over some range:
x = e-0.05t sin t
y = e-0.05tcos t
z=t
If we let t vary from t = 0 to t =10π, the sine and cosine functions will vary through five cycles, while
the absolute values of x and y become smaller as t increases. This process results in the spiral curve
shown in Figure .
>>t = 0:pi/50:10*pi;
Course Code: 20EC0454 R20
>>plot3(exp(-0.05*t).*sin(t),exp(-0.05*t).*cos(t),t),...
xlabel(‘x’),ylabel(‘y’),zlabel(‘z’),grid
2 2 2
Contour Plot: z = 𝑥𝑒[(𝑥−𝑦 ) +𝑦 ], >>[X,Y] = meshgrid(-2:0.1:2);
for -2 ≤ x≤2 and >>Z = X.*exp(-((X-Y.^2).^2Y.^2));
-2 ≤ y≤2, >>contour(X,Y,Z),xlabel(‘x’),ylabel(‘y’)
with a spacing of 0.1
UNIT – V
Let x, y, and z be the number of tons each of products 1, 2, and 3 that can be produced in one week.
Using the data for reactor A, the equation for its usage in one week is
5x + 3y + 3z = 40
The data for reactor B gives
3x + 3y + 4z = 30
This matrix gives the reduced system which can be easily solved as follows:
x – 0.5z = 5 -------------------------------- (1)
y + 1.83333z =5 -------------------------- (2)
which can be easily solved as follows:
Example : Determine the forces in the three equally spaced supports that hold up a light fixture. The
supports are 5 ft apart. The fixture weighs 400 lb, and its mass center is 4 ft from the right end.
In fig.1 shows the fixture and the free-body diagram, where T1, T2, and T3, and are the tension forces in
the supports. For the fixture to be in equilibrium, the vertical forces must cancel, and the total moments
about an arbitrary fixed point—say , the right endpoint— must be zero. These conditions give the two
equations
T1 + T2 + T3 – 400 = 0
400(4) – 10T1 – 5T2 = 0
Or
T1 + T2 + T3 = 400-------------------------- (1)
10T1 + 5T2 +0T3 = 1600----------- (2)
Because there are more unknowns than equations, the set is underdetermined. Thus we cannot determine
a unique set of values for the forces.
we will write the solutions for two of the unknowns in terms of the third:
T1 = T3 - 80 and T2 = 480 - 2T3.
These two equations are equivalent to
T1 - T3 = -80
T2 + 2T3 = 480
In matrix form these are
𝑇1
1 0 −1 −80
[ ] [𝑇2] = [ ]
0 1 2 𝑇 480
3
The augmented matrix [A b] for the above set is
1 0 −1 −80
[ ]
0 1 2 480
Note that the first two columns form a 2 x 2 identity matrix. This indicates that the corresponding
equations can be solved directly for T1 and T2 in terms of T3. We can always reduce an underdetermined
set to such a form by multiplying the set’s equations by suitable factors and adding the resulting
equations to eliminate an unknown variable. The MATLAB rref function provides a procedure for
reducing an equation set to this form, which is called the reduced row echelon form. Its syntax is rref([A
b]). Its output is the augmented matrix [C d] that corresponds to the equation set Cx = d. This set is in
reduced row echelon form.
Because there are more unknowns than equations, the set is underdetermined. Thus we cannot determine
a unique set of values for the forces.
we will write the solutions for two of the unknowns in terms of the third:
T1 = T3 - 80 and T2 = 480 - 2T3.
These two equations are equivalent to
T1 - T3 = -80
T2 + 2T3 = 480
In matrix form these are
𝑇1
1 0 −1 −80
[ ] [𝑇2] = [ ]
0 1 2 𝑇 480
3
The augmented matrix [A b] for the above set is
1 0 −1 −80
[ ]
0 1 2 480
Note that the first two columns form a 2 x 2 identity matrix. This indicates that the corresponding
equations can be solved directly for T1 and T2 in terms of T3. We can always reduce an underdetermined
set to such a form by multiplying the set’s equations by suitable factors and adding the resulting
equations to eliminate an unknown variable.
A MATLAB session to check the ranks is
The MATLAB session is
>>A = [1,1,1;10,5,0];
>>b = [400;1600];
>>rank(A)
ans =
2
>>rank([A, b])
ans =
2
>>T = A\b
T=
160.0000
0
240.0000
Because the ranks of A and [A b] are equal, a solution exists. However, because the number of
unknowns is 3 and is 1 greater than the rank of A, one of the unknowns will be undetermined. An
infinite number of solutions exist, and we can solve for only two of the unknowns in terms of the third
unknown.
Course Code: 20EC0454 R20
b Solve the following equations, using the matrix inverse method.
2x1 + 9x2 =5 3x1 - 4x2 =7
The solution of the scalar equation ax = b is x = b/a if a ≠0. The division operation of scalar
algebra has an analogous operation in matrix algebra.
Ax=b ----------------------- eq(1)
For example, to solve the matrix equation (1) for x, we must somehow “divide” b by A.
The procedure for doing this is developed from the concept of a matrix inverse.
The inverse of a matrix A is denoted by A-1 and has the property that
where I is the identity matrix. Using this property, we multiply both sides of Equation
(1) from the left by A-1 to obtain A-1 Ax = A-1b. Because A-1 A = Ix =x,
we obtain the solution
x = A-1 b ------------------------------ eq(2)
The inverse of a matrix A is defi ned only if Ais square and nonsingular. A matrix is singular if
its determinant |A| is zero. If A is singular, then a unique solution to Equation (1) does not
exist. The MATLAB functions inv(A) and det(A) compute the inverse and the determinant of
the matrix A. If the inv(A) function is applied to a singular matrix, MATLAB will issue a
warning to that effect.
The matrix A and the vector b are
A= |2 9 | 𝑏 = [5 ]
3 −4 7
The session on MATLAB is
>> A = [2 9;3 -4];
>>b= [5;7];
>>x= inv(A)*b;
>> x =
2.3714
0.0286
The solution is x1=2.3714 and x2= 0.0286 . MATLAB did not issue warning so the solution is
unique
a Describe Matrix functions and commands for solving linear equations.
Matrix function and commands for solving linear equations are listed in the table.
Function Description
det(A) Computes the determinant of the array A.
5.4375
2.0625
a Explain Flowchart illustrating a program to solve linear equations with MATLAB code.
the set of linear algebraic equations Ax=_ b with m equations and n unknowns has solutions if
and only if (1) rank[A] = rank[A b].
Table .1 pseudocode for the linear equation solver
If the rank of A equals the rank of [A b], then
determine whether the rank of A equals the number of unknowns. If so, there is a
unique solution, which can be computed using left division. Display the results
and stop.
Otherwise, there are an in nite number of solutions, which can be found from
the augmented matrix. Display the results and stop.
Otherwise (if the rank of A does not equal the rank of [A b]), there are no solutions.
Display this message and stop.
Let r = rank[A]. If condition (1) is satisfied and if r = n, then the solution is unique. If condition
(1) is satisfied but r <n, an infinite number of solutions exist; in addition, r unknown variables
can be expressed as linear combinations of the other n - r unknown variables, whose values are
arbitrary. In this case we can use the rref command to find the relations between the variables.
The pseudocode in Table 1 can be used to outline an equation solver program before writing it.
6
A condensed flowchart is shown in Figure 8.5.1. From this chart or the pseudocode, we can
develop the script le shown in Table 2. The program uses the given arrays A and b to check the
rank conditions; the left division method to obtain the solution, if one exists; and the rref
method if there are an in finite number of solutions. Note that the number of unknowns equals
the number of columns in A, which is given by size_A (2), the second element in size_A.
Note also that the rank of A cannot exceed the number of columns in A.
Table 2
% Script file lineq.m
% Solves the set Ax = b, given A and b.
% Check the ranks of A and [A b].
if rank(A) == rank([A b])
% The ranks are equal.
size_A = size(A);
% Does the rank of A equal the number of unknowns?
if rank(A) == size_A(2)
% Yes. Rank of A equals the number of unknowns.
disp(‘There is a unique solution, which is:’)
Course Code: 20EC0454 R20
x = A\b % Solve using left division.
else
% Rank of A does not equal the number of unknowns.
disp(‘There is an in nite number of solutions.’)
disp(‘The augmented matrix of the reduced system is:’)
rref([A b]) % Compute the augmented matrix.
end
else
% The ranks of A and [A b] are not equal.
disp(‘There are no solutions.’)
end
3 2 -9
-9 -5 2
6 7 3
>> b=[-65;16;5]
b=
-65
16
5
>> x = A\b
x=
2.0000
-4.0000
7.0000
a Explain how least square method is helpful to solve Over determined Systems .
When we want to solve systems of linear equations, ŷ = Xβ, we need as many equations as unknowns.
We also hope that each equation give unique information, or that it is independent of the other equations.
When the number of unknowns is equal to the number of equations there may exist a single unique
solution. In the case where there are more unknowns than equations we say that the system is
underdetermined since we have no way to uniquely solve for every unknown. A more common case is
when there are more equations than unknowns, in this case the system is overdetermined and we have
many possible solutions, but no single unique one. The problem then becomes, how to identify
satisfactory solutions. This leads to the development of the concept of error and cost. We typically define
error as the difference between expected (ŷ) and observed (y) values,
Ɛ = Xβ – y
In the majority of situations we define a cost function as the sum of all of squared errors that a given
candidate solution produces. We then hope to minimize this cost function.
minβ||Xβ − y||
Let us suppose ,we have the following three data points, and we want to find the straight line y = c1x + c2
that best fits the data in some sense.
7 x y
0 5
5 6
10 11
Because two points define a straight line, unless we are extremely lucky, our three data points will not lie
on the same straight line. A common criterion for obtaining the straight line that best fits the data is the
least-squares criterion. According to this criterion, the line that minimizes J, the sum of the squares of
the vertical differences between the line and the data points, is the “best” t. Here J is
3
% File cable.m
s34 = sqrt(34);
s35 = sqrt(35);
s42 = sqrt(42);
A1 = [1/s35, -3/s34, 1/s42];
A2 = [3/s35, 0, -4/s42];
A3 = [5/s35, 5/s34, 5/s42];
A = [A1; A2; A3];
b = [0; 0; 1];
rank(A)
rank([A, b])
T = A\b
When this file is executed by typing cable, we find that rank( A) = rank ([A b]) = 3 and obtain the
values T1 = 0.5071, T2 = 0.2915, and T3 = 0.4166. Because A is 3 X 3 and rank(A) = 3, which is the
number of unknowns, the solution is unique. Using the linearity property, we multiply these results by
mg and obtain the general solution T1 = 0.5071 mg, T2 = 0.2915 mg, and T3 = 0.4166 mg.
The session is
8 >>A = [2, 9; 3, -4]; b = [5 ; 7];
>>x = inv(A)*b
x=
2.3714
0.0286
The solution is x1 = 2.3714 and x2= 0.0286. MATLAB did not issue a warning, so the solution is unique.
b For what cases left division method gives error? Explain
The left division method works for square and non-square A matrices. However, if A is not square, the
left division method can give answers that might be misinterpreted. We will show how to interpret
MATLAB results correctly. When there are fewer equations than unknowns, the left division method
Course Code: 20EC0454 R20
might give a solution with some of the unknowns set equal to zero, but this is not the general solution.
An infinite number of solutions might exist even when the number of equations equals the number of
unknowns. This can occur when |A| = 0. For such systems the left division method generates an error
message warning us that the matrix A is singular.
consider the example eq (1)-(3) where set does not have a unique solution.
2x1 - 4x2 + 5x3 = - 4 ---------------- eq(1)
-4x1 - 2x2 + 3x3 = 4-------------------------- eq(2)
2x1 + 6x2 - 8x3 = 0---------------------- eq(3)
Because there are more unknowns than equations, the set is underdetermined. Thus we cannot determine
a unique set of values for the forces.
we will write the solutions for two of the unknowns in terms of the third:
T1 = T3 - 80 and T2 = 480 - 2T3.
These two equations are equivalent to
Course Code: 20EC0454 R20
T1 - T3 = -80
T2 + 2T3 = 480
In matrix form these are
𝑇1 −80
1
0 −1 ]
[ ] [𝑇2] = [
0
1 2 480
𝑇3
The augmented matrix [A b] for the above set is
1 0 −1 −80 ]
[
0 1 2 480
Note that the first two columns form a 2 x 2 identity matrix. This indicates that the corresponding
equations can be solved directly for T1 and T2 in terms of T3. We can always reduce an underdetermined
set to such a form by multiplying the set’s equations by suitable factors and adding the resulting
equations to eliminate an unknown variable.
A MATLAB session to check the ranks is
The MATLAB session is
>>A = [1,1,1;10,5,0];
>>b = [400;1600];
>>rank(A)
ans =
2
>>rank([A, b])
ans =
2
>>T = A\b
T=
160.0000
0
240.0000
Because the ranks of A and [A b] are equal, a solution exists. However, because the number of
unknowns is 3 and is 1 greater than the rank of A, one of the unknowns will be undetermined. An
infinite number of solutions exist, and we can solve for only two of the unknowns in terms of the third
unknown.
For underdetermined sets, MATLAB provides three ways of dealing with the equation set
Ax = b (note that the matrix inverse method will never work with such sets):
1. The matrix left division method (which gives one specific solution, but not the general
solution).
2. The pseudoinverse method. Solve for x by typing x = pinv(A)*b. This gives the minimum
norm solution.
3. The reduced row echelon form (RREF) method. This method uses the MATLAB command
rref to obtain a general solution for some of the unknowns in terms of the other unknowns.
2) Overdetermined system: The overdetermined case occurs when the equation set has more
independent equations than unknowns. An overdetermined system is a set of equations that has more
independent equations than unknowns. Some overdetermined systems have exact solutions, and they can
be obtained with the left division method x = A\b.
For other overdetermined systems, no exact solution exists; in some of these cases, the left division
method does not yield an answer, while in other cases the left division method gives an answer that
satisfies the equation set only in a “least-squares” sense. To interpret MATLAB answers correctly
for an overdetermined system, first check the ranks of matrix A and augmented matrix [A b] to
see if an exact solution exists; if one does not exist, then we know that the left division answer
is a least-squares solution.
Example : Let us suppose ,we have the following three data points, and we want to find the straight line
y = c1x + c2 that best fits the data in some sense.
x y
0 5
5 6
10 11
Course Code: 20EC0454 R20
To use left division, the MATLAB session is
>>A = [0,1;5,1;10,1];
>>b = [2;6;11];
>>rank(A)
Ans
=2
>>rank([A, b])
Ans
=3
>>x = A\b
x=
0.9000
1.8333
>>A*x
ans =
1.833
6.333
10.8333
This result for x agrees with the least-squares solution obtained previously: c1 = 0.9, c2 = 11/6 = 1.8333.
The rank of A is 2, but the rank of [A b] is 3, so no exact solution exists for c1 and c2. Note that A*x
gives the y values generated by the line y = 0.9x + 1.8333 at the x data values x = 0, 5, 10.
b Discuss different methods of transfer functions in MATLAB with examples.
1. By Using Equation
2. By Using Coefficients
syntax: zpk([zeros],[poles],gain)
Matlab Program
h=
100(𝑠 − 1)(𝑠 + 2)
(𝑠 − 2)(𝑠 − 3)(𝑠 − 4)
>>pzmap(h)
tf(h)
ans =