Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Matlab Q&a

Download as pdf or txt
Download as pdf or txt
You are on page 1of 85

Course Code: 20EC0454 R20

SIDDHARTH INSTITUTE OF ENGINEERING & TECHNOLOGY:: PUTTUR


(AUTONOMOUS)
Siddharth Nagar, Narayanavanam Road – 517583
QUESTION BANK (DESCRIPTIVE)

Subject with Code: MATLAB PROGRAMMING (20EC0454)


Course & Branch: B.Tech – CSE, CSIT, & CSM
Regulation: R20
Year & Sem: IV-B.Tech & I-Sem

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!

Matlab Input Program


>>A= [6 ,-4 , 8;-5, -3, 7; -5 ,-2 ,4]
>>B=[112 ; 75; 25]
>>X = A\B
Output:
Course Code: 20EC0454 R20

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:

5 a Discuss the functions of Menus and Tool bars available in MATLAB.


Functions ofMenus:
The Editor/Debugger menu bar contains the following items: File, Edit, Text, Go, Cell, Tools, Debug,
Desktop, Window, and Help. The File, Edit, Desktop Window, and Help menus are similar to those in
the Desktop.
The Go menu lets you go backward or forward in the file.
The Cell menu will be discussed shortly.
The Desktop menu is similar to that in the Command window. It enables you to dock and undock
windows, arrange the Editor window, and turn the Editor toolbar on and off.
Below the menu bar is the Editor/Debugger toolbar. It enables you to access several of the items in the
menus with one click of the mouse. Hold the mouse cursor over a button on the toolbar to see its
function.
For example, clicking the button with the binoculars icon is equivalent to selecting Find and Replace
from the Edit menu. One item on the toolbar that is not in the menus is the function button with the script
f icon (f). Use this button to go to a particular function in the M-file.
The list of functions will includes only those functions whose function statements are in the program.
The list does not include functions that are called from the M- file. The Text menu supplements the Edit
menu for creating M- files.
With the Text menu you can insert or remove comments, increase or decrease the amount of indenting,
turn on smart indenting, and evaluate and display the values of selected variables in the Command
window. Click anywhere in a previously typed line, and then click Comment in the Text menu. This
makes the entire line a comment. To turn a commented line into an executable line, click anywhere in
the line, and then click Uncomment in the Text menu.
Functions of Tool bars:
The default configuration of the MATLAB desktop is shown in Figure 1.1. It integrates many tools for
managing files, variables, and applications within the MATLAB environment.
The major tools within or accessible from the MATLAB desktop are:
■■ The Command Window
■■ The Toolstrip
■■ The Documents Window, including the Editor/Debugger and Array Editor
■■ Figure Windows
■■ The Workspace Browser
■■ The Current Folder Browser, with the Details Window
■■ The Help Browser
■■ The Path Browser
■■ A Popup Command History Window
b List applications, advantages and disadvantages of MATLAB.
Advantages:The following are the advantages of the MATLAB
1. Ease of Use: MATLAB is an interpreted language, like many versions of Basic. Like Basic, it is very
easy to use. The program can be used as a scratch pad to evaluate expressions typed at the command
line, or it can be used to execute large prewritten programs. Programs may be easily written and
modified with the built-in integrated development environment, and debugged with the MATLAB
debugger. Because the language is so easy to use, it is ideal for the rapid prototyping of new programs.
Many program development tools are provided to make the program easy to use. They include an
integrated editor/debugger, on-line documentation and manuals, a workspace browser, and extensive
demos.
2. Platform Independence: MATLAB is supported on many different computer systems, providing a
large measure of platform independence. At the time of this writing, the language is supported on
Windows 2000/XP/Vista, Linux, several versions of Unix, and the Macintosh. Programs written on any
platform will run on all of the other platforms, and data files written on any platform may be read
transparently on any other platform. As a result, programs written in MATLAB can migrate to new
platforms when the needs of the user change.
Course Code: 20EC0454 R20
3. Predefined Functions: MATLAB comes complete with an extensive library of predefined functions
that provide tested and prepackaged solutions to many basic technical tasks. For example, suppose that
you are writing a program that must calculate the statistics associated with an input data set. In most
languages, you would need to write your own subroutines or functions to implement calculations such as
the arithmetic mean, standard deviation, median, and so on. These and hundreds of other functions are
built right into the MATLAB language, making your job much easier. In addition to the large library of
functions built into the basic MATLAB language, there are many special-purpose toolboxes available to
help solve complex problems in specific areas. For example, a user can buy standard toolboxes to solve
problems in signal processing, control systems, communications, image processing, and neural networks,
among many others. There is also an extensive collection of free user-contributed MATLAB programs
that are shared through the MATLAB Web site.
4. Device-Independent Plotting: Unlike most other computer languages, MATLAB has many integral
plotting and imaging commands. The plots and images can be displayed on graphical output device
supported by the computer on which MATLAB is running. This capability makes MATLAB an
outstanding tool for visualizing technical data.
5. Graphical User Interface: MATLAB includes tools that allow a programmer to interactively
construct a Graphical User Interface (GUI) for his or her program. With this capability, the programmer
can design sophisticated data-analysis programs that can be operated by relatively inexperienced users.
6. MATLAB Compiler: MATLAB’s flexibility and platform independence is achieved by compiling
MATLAB programs into a device-independent p-code and then interpreting the p-code instructions at
runtime. This approach is similar to that used by Microsoft’s Visual Basic language. Unfortunately, the
resulting programs can sometimes execute slowly because the MATLAB code is interpreted rather than
compiled. We will point out features that tend to slow program execution when we encounter them. A
separate MATLAB compiler is available. This compiler can compile a MATLAB program into a true
executable that runs faster than the interpreted code. It is a great way to convert a prototype MATLAB
program into an executable suitable for sale and distribution to users.
Disadvantages:
MATLAB has two principal disadvantages.
The first is that it is an interpreted language and therefore may execute more slowly than compiled
languages. This problem can be mitigated by properly structuring the MATLAB program.
The second disadvantage is cost: a full copy of MATLAB is five to ten times more expensive than a
conventional C or Fortran compiler. This relatively high cost is more than offset by the reduced time
required for an engineer or scientist to create a working program, so MATLAB is cost-effective for
businesses. However, it is too expensive for most individuals to consider purchasing. Fortunately, there
is also an inexpensive Student Edition of MATLAB, which is a great tool for students wishing to learn
the language. The Student Edition of MATLAB is essentially identical to the full edition.
6 a How are the elements in the array arranged in the computer’s memory?
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. MATLAB always allocates array
elements in column major order. That is, MATLAB allocates the first column in memory, then the
second, then the third, and so on., until all of the columns have been allocated. Figure 2.3 illustrates this
memory allocation scheme for an array a. As we can see, element a(1,2) is really the fifth element
allocated in memory.
Course Code: 20EC0454 R20

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).

b Illustrate the MATLAB plotting commands with examples.


MATLAB contains many powerful functions for easily creating plots of several different types, such as
rectilinear, logarithmic, surface, and contour plots.

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.

Fig. a) Rectilinear plot b) Log-log plot


2 2+0.02x2
100(1 − 0.01x )
y= √ 0.1 ≤ x ≤ 100
(1 − x ) + x2
2 2

% Create the Rectilinear Plot


x1 = 0:0.01:100;
u1 = x1.^2;
num1 = 100*(1-0.01*u1).^2 + 0.02*u1;
den1 = (1-u1).^2 + 0.1*u1;
y1 = sqrt(num1./den1);
subplot(1,2,1), plot(x1,y1),xlabel(‘x’),ylabel(‘y’),
% Create the Loglog Plot
x2 = logspace(-2, 2, 500);
u2 = x2.^2; num2 = 100*(1-0.01*u2).^2 + 0.02*u2;
den2 = (1-u2).^2 + 0.1*u2;
y2 = sqrt(num2./den2);
subplot(1,2,2), loglog(x2,y2),xlabel(‘x’),ylabel(‘y’)
Course Code: 20EC0454 R20
Polar Plot: For polar plot of function
2
r = 1−0.5𝑐𝑜𝑠𝜃
>>theta = 0:pi/90:2*pi;
>>r = 2./(1-0.5*cos(theta));
>>polar(theta,r),title(‘Orbital Eccentricity = 0.5’)

7 a Discuss MATLAB search Path.


MATLAB has a search path that it uses to find M-files. MATLAB’s M-files are organized in directories
on your file system. Many of these directories of M-files are provided along with MATLAB, and users
may add others. If a user enters a name at the MATLAB prompt, the MATLAB interpreter attempts to
find the name as follows:
1. It looks for the name as a variable. If it is a variable, MATLAB displays the current contents of the
variable.
2. It checks to see if the name is an M-file in the current directory. If it is, MATLAB executes that
function or command.
3. It checks to see if the name is an M-file in any directory in the search path. If it is, MATLAB executes
that function or command.
Note that MATLAB checks for variable names first, so if you define a variable with the same name as a
MATLAB function or command, that function or command becomes inaccessible. This is a common
mistake made by novice users.
Also, if there is more than one function or command with the same name, the first one found on the
search path will be executed and all of the others will be inaccessible. This is a common problem for
novice users, since they sometimes create M-files with the same names as standard MATLAB functions,
making them inaccessible.
MATLAB includes a special command (which) to help you find out just which version of a file is being
executed and where it is located. This can be useful in finding filename conflicts. The format of this
command is which functionname, where functionname is the name of the function that you are trying to
locate. For example, the cross-product function cross.m can be located as follows:
» which cross C:\Program Files\MATLAB\R2007a\toolbox\matlab\specfun\cross.m
The MATLAB search path can be examined and modified at any time by selecting “Desktop Tools/Path”
from the Start Button, or by typing edit path in the Command Window. The Path Tool allows a user to
add, delete, or change the order of directories in the path. Other path-related functions include addpath—
Add directory to MATLAB search path.
path—Display MATLAB search path.
path2rc—Add current directory to MATLAB search path.
rmpath—Remove directory from MATLAB search path.
b Explain different MATLAB files for file storage.

8 a Differentiate script file and function file.


Script files are collections of MATLAB statements that are stored in a file. Script files share the
Command Window’s workspace, so any variables that were defined before the script file starts are
visible to the script file, and any variables created by the script file remain in the workspace after the
script file finishes executing.

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

b Compute volume of sphere of radius 5 cm using a MATLAB script.


To write the MATLAB following steps are being followed:
1) State the problem: The problem statement for the given problem is very simple. We want to
write a program that will calculate the volume of the sphere of radius 5cm.
2) Define the inputs and outputs: The inputs required by this program is the radius only.
The output from the program will be the volume of sphere V.
3) Design the algorithm: This task can be broken down into three major sections, whose functions
are input, processing, and output:
Define the input variable for radius and assign the value to the variable. Calculate the volume of
the sphere using standard formula V = 4/3π r3. Write out the volume value on the screen.

%Program for computation of volume of the sphere


%created on 18 March 2022 by Dr. Savitesh
%input variable and assign the value
r = 5; %radius of the sphere is 5 cm
%Calculation section
V= 4/3*pi*r^3; %V is volume of the sphere in cm^3
%display section
str = ['Volume of the sphere = ' num2str(V)];
disp (str);
Note that pi is predefined to be the value 3.141592 .

9 a Compare local variable and global variable in MATLAB.


All the variables in a function file are local (the input and output arguments and any variables that are
assigned values within the function file). This means that the variables are defined and recognized only
Course Code: 20EC0454 R20
inside the function file.
Global Variable Local variable
Whenever we want to make a variable common Whenever we want to make a variable in a single
(recognized) in several different function files, function file which are not shared with other
and perhaps in the workspace too that variable is functions or with the workspace of the Command
called Global variable. This is done by Window and the script files that variables are
called local variables.
Declaration of the variable global is done with the Declaration of the variable local is done without
global command. For example the global command. For example
global GRAVITY_CONST FrictionCoefficient GRAVITY_CONST=9.8
Several variables can be declared global by Several variables can be declared local by
listing them, separated with spaces, in the global initializing them separately in the individual
command. lines.
The variable has to be declared global in every Local Variable in each function with same will be
function file that the user wants it to be treated as individual variable.
recognized in. The variable is then common only
to these files.

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

b How variables are initializing in MATLAB.


MATLAB variables are automatically created when they are initialized. There are three common ways to
initialize a variable in MATLAB:
1. Assign data to the variable in an assignment statement.
2. Input data into the variable from the keyboard.
3. Read data from a file.
Initializing variables in Assignment Statements:
The simplest way to initialize a variable is to assign it one or more values in an assignment statement.
An assignment statement has the general form var = expression; where var is the name of a variable, and
expression is a scalar constant, an array, or a combination of constants, other variables, and mathematical
operations (, , etc.). The value of the expression is calculated using the normal rules of mathematics, and
the resulting values are stored in named variable. The semicolon at the end of the statement is optional.
If the semicolon is absent, the value assigned to var will be echoed in the Command Window. If it is
present, nothing will be displayed in the Command Window even though the assignment has occurred.
Simple examples of initializing variables with assignment statements include
var = 40i;
var2 = var/5;
x = 1;
y = 2;
array = [1 2 3 4];
The first example creates a scalar variable of type double and stores the imaginary number 40i in it. The
second example creates a scalar variable and stores the result of the expression var/5 in it. The third
example shows that multiple assignment statements can be placed on a single line, provided that they are
separated by semicolons or commas. Note that if any of the variables had already existed when the
statements were executed, then their old contents would have been lost. The last example shows that
variables can also be initialized with arrays of data. Such arrays are constructed using brackets ([]) and
semicolons. All of the elements of an array are listed in row order. In other words, the values in each row
are listed from left to right, with the topmost row first and the bottommost row last. Individual values
Course Code: 20EC0454 R20
within a row are separated by blank spaces or commas, and the rows them.
selves are separated by semicolons or new lines. The following expressions are all legal arrays that can
be used to initialize a variable:
Initializing with shortcut Expression:
It is easy to create small arrays by explicitly listing each term in the array, but what happens when the
array contains hundreds or even thousands of elements? It is just not practical to write out each element
in the array separately! MATLAB provides a special shortcut notation for these circumstances using the
colon operator. The colon operator specifies a whole series of values by specifying the first value in the
series, the stepping increment, and the last value in the series. The general form of a colon operator is
first:incr:last where first is the first value in the series, incr is the stepping increment, and last is the last
value in the series. If the increment is one, it may be omitted. This operator will generate an array
containing the values first, first+incr, first+2*incr, first+3*incr, and so forth as long as the values are
less than or equal to last. The list stops when the next value in the series is greater than the value of last.
For example, the expression 1:2:10 is a shortcut for a 1 X 5 row vector containing the values 1, 3, 5, 7,
and 9. The next value in the series would be 11, which is greater than 10, so the series terminates at 9.
» x = 1:2:10
x = 1 3 5 7 9.
Shortcut expressions can be combined with the transpose operator (') to initialize column vectors and
more complex matrices
f = [1:4]';
Initializing with Built-in Function:
Arrays can also be initialized using built-in MATLAB functions. For example, 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);
c = [1 2; 3 4];
d = zeros(size(c));
Initializing with Keyboard Inputs:
It is also possible to prompt a user and initialize a variable with data that he or she types directly at the
keyboard. This option allows a script file to prompt a user for input data values while it is executing. The
input function displays a prompt string in the Command Window and then waits for the user to type in a
response. For example, consider the following statement:
my_val = input('Enter an input value:')
When this statement is executed, MATLAB prints out the string 'Enter an input value:', and then waits
for the user to respond. If the user enters a single number, it may just be typed in. If the user enters an
array, it must be enclosed in brackets.
10 a Calculate first 10 numbers of Fibonacci series and Display on MATLAB.
The nth Fibonacci number is defined by the following recursive equations:
ƒ(1)=1
f(2) =2
f(n)= f(n-1)+f(n-2)
Therefore, f(3) = f(1)+f(2) = 1+2 =3
and so forth for higher numbers.
To write the matlab program we will use while loop
%Program for generating Fibonacci number
%initialise the variable
n=10
x=10-n
f[1]=1
f[2]=2
while x<=0
f[x]=f[x-1]+f[x2];
b Examine the following MATLAB statements. Are they correct or incorrect? If they are correct,
Course Code: 20EC0454 R20
what do they output? If they are incorrect, what is wrong with them?
If volts>125
disp(‘WARNING: HIGH voltage on line:’);
If volts>105
disp(‘WARNING: LOW voltage on line:’);
else
disp(‘Line voltage is within tolerances.’)
end
These statement are incorrect. For this structure to work, the second if statement would need to be an
elseif statement.

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

Fig.2 Representations of one- and two-dimensional arrays


Operations on Arrays:
The array is a homogeneous structure, i.e. the elements of an array are of the same type. It is
finite; it has a specified number of elements. An array is ordered; there is an ordering of elements
in it as zeroth, first, second etc. Following set of operations are defined for this structure.
i) Creating an array
ii) Initialising an array
iii) Storing an element
iv) Retrieving an element
v) Inserting an element
vi) Deleting an element
vii) Searching for an element
viii) Sorting elements
ix) Printing an array
Course Code: 20EC0454 R20
Explain how Array addressing is done in MATLAB, give some examples.
b “Array addressing” can be used to “get numbers out of” arrays. a(i) refers to the i number in an array
a with one row.
What statements are used to control the operation of while loops and for loops?
There are two additional statements that can be used to control the operation of while loops and for
loops: the break and continue statements. The break statement terminates the execution of a loop and
passes control to the next statement after the end of the loop, while the continue statement terminates
the current pass through the loop and returns control to the top of the loop. If a break statement is
executed in the body of a loop, the execution of the body will stop, and control will be transferred to
the first executable statement after the loop. An example of the break statement in a for loop is shown
here.
for ii = 1:5
if ii == 3;
break;
end
fprintf('ii = %d\n',ii);
end
disp(['End of loop!']);
When this program is executed, the output is
» test_break
ii = 1
ii = 2
End of loop!
Note that the break statement was executed on the iteration when ii was 3, and control transferred to
a the first executable statement after the loop without executing the fprintf statement. If a continue
statement is executed in the body of a loop, the execution of the current pass through the loop will
stop, and control will return to the top of the loop.
2 The controlling variable in the for loop will take on its next value, and the loop will be executed
again. An example of the continue statement in a for loop is shown here.
for ii = 1:5
if ii == 3;
continue;
end
fprintf('ii = %d\n',ii);
end
disp(['End of loop!']);
When this program is executed, the output is
» test_continue
ii = 1
ii = 2
ii = 4
ii = 5
End of loop!
Note that the continue statement was executed on the iteration when ii was 3, and control will be
transferred to the top of the loop without executing the fprintf statement. The break and continue
statements work with both while loops and for loops.
Describe in brief about multidimensional array with some examples.
MATLAB allows us to create arrays with as many dimensions as necessary for any given problem.
b These arrays have one subscript for each dimension, and an individual element is selected by
specifying a value for each subscript. The total number of elements in the array will be the product of
the maximum value of each subscript.
Course Code: 20EC0454 R20

For example, the following two statements create a 2x3x2 array c:


» c(:,:,1)=[1 2 3; 4 5 6];
» c(:,:,2)=[7 8 9; 10 11 12];
» whos c
Name Size Bytes Class Attributes
c 2x3x2 96 double
This array contains 12 elements . Its contents can be displayed just like any other array
»c
c(:,:,1) =
1 2 3
4 5 6
c(:,:,2) =
7 8 9
10 11 12
There are 3 following ways to generate multidimensional array
• Generating arrays using indexing
• Generating arrays using MATLAB functions
• Using the cat function to build multidimensional arrays

1)Generating Arrays Using Indexing

One way to create a multidimensional array is to create a two-dimensional array


and extend it. For example, begin with a simple two-dimensional array A.
A = [5 7 8; 0 1 9; 4 3 6];

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]

MATLAB responds with


A(:,:,1) =
5 7 8
0 1 9
4 3 6

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.

2) Generating Arrays Using MATLAB Functions

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.

3) Building Multidimensional Arrays with the cat Function

The cat function is a simple way to build multidimensional arrays; it concatenates


a list of arrays along a specified dimension.
B = cat(dim,A1,A2...)
where A1, A2, and so on are the arrays to concatenate, and dim is the dimension
along which to concatenate the arrays. For example, to create a new array
with cat
B = cat(3,[2 8; 0 5],[1 3; 7 9])

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.

One of MATLAB’s peculiarities is that it will permit a user or programmer to treat a


multidimensional array as though it were a one-dimensional array whose length is equal to the
number of elements in the multidimensional array. If a multidimensional array is addressed with a
single dimension, then the elements will be accessed in the order in which they were allocated in
memory. For example, suppose that we declare the element array a as follows:
» a = [1 2 3; 4 5 6; 7 8 9; 10 11 12]
a=
1 2 3
4 5 6
7 8 9
10 11 12
Then the value of a(5) will be 2, which is the value of element a(1,2), because a(1,2)was allocated
fifth in memory.
Write Element-by-Element operation on
(i) Array Addition and Subtraction
(ii) Element-by-Element Multiplication
(i) Element-by-Element operation on Array Addition and Subtraction: Array
operations are operations performed between arrays on an element-by-element basis.
That is, the operation is performed on corresponding elements in the two arrays. For
1 2 −1 3
array addition operation consider example, if a =[ ] and b=[ ] , then a+b
3 4 −2 1
0 5
=[ ].
1 5
1 2 −1 3
For array addition operation consider example, if a =[ ] and b=[ ] , then a-b
3 a 3 4 −2 1
2 −1
=[ ] . Note that for these operations to work, the number of rows and columns in
5 3
both arrays must be the same. If not, MATLAB will generate an error message.
(ii) Element-by-Element Multiplication: MATLAB defines element-by-element
multiplication only for arrays that are the same size. The definition of the product x.*y,
where x and y each have n elements, is x.*y = [x(1)y(1), x(2)y(2) . . . , x(n)y(n)] For
array multiplication, MATLAB uses a period before the symbol to indicate an array
1 2 −1 3
operation (for example, .*). consider example, if a =[ ] and b=[ ] , then a.*b
3 4 −2 1
−1 6
=[ ].
−6 4
Course Code: 20EC0454 R20
What is the purpose of varargin? How does it works?
Function varargin appears as the last item in an input argument list, and it returns a cell array
containing all of the actual arguments specified when the function is called, each in an individual
element of a cell array. This function allows a MATLAB function to support any number of input
arguments.
A special input argument, varargin, is available within user-defined MATLAB functions to support
variable numbers of input arguments. This argument appears as the last item in an input argument list,
and it returns a cell array; thus, a single dummy input argument can support any number of actual
arguments. Each actual argument becomes one element of the cell array returned by varargin. If it is
used, varargin must be the last input argument in a function, following all of the required input
arguments. For example, suppose that we are writing a function that may have any number of input
arguments. This function could be implemented as shown here:
function test1(varargin)
disp(['There are ' int2str(nargin) ' arguments.']);
b disp('The input arguments are:');
disp(varargin);
When this function is executed with varying numbers of arguments, the results are
» test1
There are 0 arguments.
The input arguments are:
» test1(6)
There are 1 arguments.
The input arguments are:
[6]
» test1(1,'test 1',[1 2;3 4])
There are 3 arguments.
The input arguments are:
[1] 'test 1' [2x2 double]

Write Element-by-Element operation on


(i) Element-by-Element Division
(ii) Element-by-Element Exponentiation
(i) Element-by-Element division: The definition of element-by-element division,
also called array division, is similar to the definition of array multiplication
except, of course, that the elements of one array are divided by the elements of
the other array. Both arrays must be the same size. The symbol for array right
division is . /.
For example, if =[8 12 15] and y=[-2 6 5] then z = x./y gives = z= [8/-2 12/6 15/5]
Also, 24/−4 20/5
24 20 −4 5 −6 4
if then A=[ ] B=[ ] C = A./B gives C=[ ] =[ ]
−9 4 3 2 −9/3 4/2 3 2

The array left division operator (.\) is defined to perform element-by-element division
4 a using left division. Note that A.\B is not equivalent to A./B
Note that for these operations to work, the number of rows and columns in both arrays must be
the same. If not, MATLAB will generate an error message.
(ii) Element-by-Element Exponentiation: MATLAB enables us not only to raise
arrays to powers but also to raise scalars and arrays to array powers. To perform
exponentiation on an element-by-element basis, we must use the .^ symbol. For
example, if x = [3, 5, 8], then typing x.^3 produces the array [33 , 53 , 83 ] = [27,
125, 512].
If x = 0:2:6, then typing x.^2 returns the2 array [02 , 22 , 42 , 62 ] = [0, 4, 16, 36].
−4 5 (−4) 52 16 25
If 𝐴 = [ ] then B=A.^2 = [ ]= [ ]
3 2 32 22 9 4
We can raise a scalar to an array power. For example, if p = [2, 4, 5], then typing 3.^p produces the
array [32 , 34 , 35 ] = [9, 81, 243].
With array exponentiation, the power may be an array if the base is a scalar or if the power’s
dimensions are the same as the base dimensions. For example if, x = [1,2,3] and y = [2,3,4], then y.^x
Course Code: 20EC0454 R20
» a{1,1}
ans =
1 3 -7
2 0 6
0 5 1
3 3 3
In summary, the notation a(1,1) refers to the contents of cell a(1,1) (which is a data structure), while
the notation a{1,1} refers to the contents of the data structure within the cell.
Therefore, A cell array is an array of “pointers.” each element of which can point to any type of
MATLAB data.
How it differs from ordinary array:
It differs from an ordinary array in that each element of a cell array can point to a different type of
data, such as a numeric array, a string, another cell array, or a structure. Also, cell arrays use braces
{} instead of parentheses () for selecting and displaying the contents of cells.
Explain about polynomial operations using arrays with examples.
Polynomials are mathematical expressions that are frequently used for problem solving and modeling
in science and engineering. In many cases an equation that is written in the process of solving a
problem is a polynomial, and the solution of the problem is the zero of the polynomial. MATLAB has
a wide selection of functions that are specifically designed for handling polynomials.
Polynomials are functions that have the form:
F(x) = anxn+ an-1xn-1+............... + a1x1+ a0x0

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

For example : f(x) = x2 - 2 x – 3 , The value of f(1) is -4. MatLab program


>>p = [1 -2 -3]
>> r = roots(p)
Ans =
-1
3

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:

Function to cricshift array contents:This functionShift array circularly.


Syntax
• B = circshift(A,shiftsize)
Description
B = circshift(A,shiftsize) circularly shifts the values in the array, A,
by shiftsize elements. shiftsize is a vector of integer scalars where the n-th element specifies
the shift amount for the n-th dimension of array A. If an element in shiftsize is positive, the
values of A are shifted down (or to the right). If it is negative, the values of A are shifted up
(or to the left). If it is 0, the values in that dimension are not shifted.
B = circshift(A,1)
B=789
123
456
Circularly shift first dimension values down by 1 and second dimension values to the left by
1.
B = circshift(A,[1 -1]);
B=897
231
564

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

Fig.1 Arrangement of data in the structure array student.

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.

Given the matrices


A=[ 21 27] B=[−7 −3]
−18 8 9 4
Find (i) their array product,
(ii) their array right division ( A divided by B), and
(iii) ‘B’ raised to the two power element by element.
b
(i) A=[ 21 27]B=[−7 −3]
−18 8 9 214 27 −7 −3
Array product: A*B= [ ][ ]
−18 8 9 4
=[−7 −3]
9 4
(ii)

UNIT – III
FUNCTIONS AND FILES

Discuss about elementary mathematical function with proper commands.


MATLAB has many built-in functions, including trigonometric, logarithmic, and hyperbolic functions,
as well as functions for processing arrays. These functions areknown as elementary mathematical
function.We can categories elementary mathematical function as follows:
1)Exponential and Logarithmic Function:
One of the strengths of MATLAB is that it will treat a variable as an array automatically. For example,
to compute the square roots of 5, 7, and 15, type
a >>x = [5,7,15];
y = sqrt(x)
y = 2.2361 2.6358 3.8730
The square root function operates on every element in the array x.
Similarly, we can type exp(2) to obtain e2 =7.3891, where e is the base of the natural logarithms.
Typing exp(1) gives 2.7183, which is e.
Note that in mathematics text, ln x denotes the natural logarithm, where x =ey implies that because
Course Code: 20EC0454 R20
y
ln x=ln(e )= y ln e = y.
However, this notation has not been carried over into MATLAB, which uses log(x) to represent ln x.
The common (base-10) logarithm is denoted in text by log x or log10 x. It is defined by the relation x
=10y ; that is, because
log10x = log 10 10y =y log 10 10.
2) Complex Number Functions: 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 function conj(x) computes the complex conjugate of x
The MATLAB common logarithm function is log10(x).
>>x = -3 + 4i; y = 6 - 8i;
>>mag_x = abs(x)
mag_x
= 5.0000
>>angle_x = angle(x)
angle_x
= 2.2143
3) Numeric Functions: The round function rounds to the nearest integer. If y=[2.3,2.6,3.9],
typing round(y) gives the results 2, 3, 4. The x function truncates to the nearest integer toward
zero. Typing x(y) gives the results 2, 2, 3. The ceil function (which stands for “ceiling”) rounds
to the nearest integer toward . Typing ceil(y) produces the answers 3, 3, 4.
4) Trigonometric Functions : Other commonly used functions are cos(x), tan(x), sec(x), and
csc(x), which return cos x, tan x, sec x, and csc x, respectively. MATLAB trigonometric
functions that operate in radian mode. Thus sin(5) computes the sine of 5 rad, not the sine of
5#. Similarly, the inverse trigonometric functions return an answer in radians. The functions
that operate in degree mode have the letter d appended to their names. For example, sind(x)
accepts the value of x in degrees.
5) Hyperbolic Functions: The hyperbolic functions are the solutions of some common problems
in engineering analysis. For example :The hyperbolic sine, sinh x, is defined as
𝒙 −𝒙
sinh x= 𝒆 −𝒆
𝟐
Table: Some common elementary mathematical function
Course Code: 20EC0454 R20

Explain pre-defined constants with examples.


Pre-defined Built-in constants in MATLAB are: pi, i, inf, NaN (not a number). By writing the name of
the keyword of pre-defined constant in a program will automatically takes constant value as shown on
the list.
examples
b pi π=3.141592654…
i, j √−1, √−1 Imaginary unit
NaN, nan Not a number (i.e., division by zero)
Inf, inf Infinity

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 data output data


Function file

Syntax to create a user-defined function:


3 a function [o1, o2, o3…, on] = func_name (i1, i2, i3, …,im)
Description of the syntax:

1. func_name is the name of our function


2. o1, o2, o3, …, on are the outputs of our function
3. i1, i2, i3, …, im are the inputs of our function
for example, we will create a user-defined function to calculate the area of a circle. We will
name our function as compute_area, and so our file name will also be compute_area. Below
are the steps to be followed:

1. Initialize the function compute_area


2. Write the logic to compute the area of a circle
3. Save the file by the name compute_area
4. Call this function in the new Matlab window using the name and passing the argument

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

Fig.a A typical menu structure


Course Code: 20EC0454 R20
Fig. (b) The relationships among the uimenu items creating the menu. (c) The Menu Editor structure
that generated these menus.

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:

1. func_name is the name of our function


2. o1, o2, o3, …, on are the outputs of our function
3. i1, i2, i3, …, im are the inputs of our function
we will create a user-defined function to return the maximum number out of list of 3 given
numbers. We will name our function as max_num, and so our file name will also be
max_num. Below are the steps to be followed:

1. Initialize the function max_num


2. Write the logic to find the maximum number.
a 3. Save the file by the name max_num.
4. Call this function in the new Matlab window using the name and passing the argument

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.

Describe various MATLAB file types.


There are mainly five different types of MATLAB files for storing data or programs that we are likely
to use often:
3) M-files : M-files are standard ASCII text files, with a .m extension to the filename. There are
two types of these files: script files and junction files. Most programs you write in MATLAB
are saved as M-files. All built-in function in MATLAB are M-files, most of which reside on
your computer in precompiled format. Some built-in functions are provided with source code
in readable M-files so that they can be copied and modified.
4) Mat-files : Mat-files are binary datafiles, with a . mat extension to the filename. Mat-files are
created by MATLAB when you save data with the s ave command. The data is written in a
special format that only MATLAB can read. Mat-files can be loaded into MATLAB with the
b load command. Fig-files are binary figure files with a .fig extension that can be opened again
in MATLAB as figures. Such files are created by saving a figure in this format using the Save
or Save As options from the File menu or using the saveas command in the command
window. A fig-file contains all the information required to recreate the figure. Such files can
be opened with the open filename.fig command.
5) P-files :P-files are compiled M-files with a .p extension that can be executed in MATLAB
directly (without being parsed and compiled) . These files are created with the pcode
command. If you develop an application that other people can use but you do not want to give
them the source code (M- file) , then you give them the corresponding p-code or the p-file.
6) Mex-files :Mex-files are MATLAB-callable Fortran, C, and Java programs, with a . mex
extension to the filename. Use of these files requires some experience with MATLAB and a
lot of patience
Explain Nested function with an example.
A nested function is a user-defined function that is written inside another userdefined function. The
portion of the code that corresponds to the nested function starts with a function definition line and
ends with an end statement. An end statement must also be entered at the end of the function that
contains the nested function. (Normally, a user-defined function does not require a terminating end
statement. However, an end statement is required if the function contains one or more nested
functions.) Nested functions can also contain nested functions. Obviously, having many levels of
nested functions can be confusing. This section considers only two levels of nested functions.
One nested function: The format of a user-defined function A (called the primary function) that
contains one nested function B is:
function y=A(a1,a2)
7 a
.......
function z=B(b1,b2)
.......
end
.......
end
• Note the end statements at the ends of functions B and A.
• The nested function B can access the workspace of the primary function A, and the primary function
A can access the workspace of the function B. This means that a variable defined in the primary
function A can be read and redefined in nested function B and vice versa.
• Function A can call function B, and function B can call function A.
Course Code: 20EC0454 R20

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

EXPORT DATA TO EXCEL


To illustrate how this is done, the following example will be used. Create a simple Simulink Model
with Sine Wave, Scope, and To Workspace blocks as in Fig. 1.

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

Prompt the user for the values x and y.

Read x and y

if x ≥ 0 and y ≥ 0

fun <- x+y

elseif x ≥ 0 and y < 0

fun <-x + y^ 2

elseif x < 0 and y ≥ 0

fun < x^2 + y

else

fun <- x^2 + y^2

end

Write out f(x,y)

4. Now turn the algorithm into MATLAB statements.

The final MATLAB code is shown below.

%script file funxy.m

%This program solves the function f(x, y) for a user-specified x and y, where %f(x,y) is
defined as:

x= input ("Enter the x coefficient: ");

y= input ('Enter the y coefficient: ");

if x >= 0 && y >= 0

fun = x + y;

elseif x >= 0 a< 0

fun = x + y^ 2 ;

elseif x < 0 && y >= 0

fun = x^2 + y

else
Course Code: 20EC0454 R20
fun = x^2 + y^2

end

%write the value of the function.

disp ([‘The value of the function is ‘ num2str(fun)] );

5. Test the program.

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

f(-2,-3) = (-2) 2 + (-3) 2 = 13

If this program is compiled, and then run four times with the above values, the results are:

>> funxy

Enter the x coefficient: 2

Enter the y coefficient: 3

The value of the function is 5

» funxy

Enter the x coefficient: 2

Enter the y coefficient: -3

The value of the function is 11

» funxy

Enter the x coefficient: -2

Enter the y coefficient: 3

The value of the function is 7

>>funxy

Enter the x coefficient: -2

Enter the y coefficient: -3

The value of the function is 13 possible cases.

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

Explain ceil() , fix(), floor(), round() and sign() with examples.


Mathematical Function
ceil(x) :Round to the nearest integer toward .
The ceil function (which stands for “ceiling”) rounds to the nearest integer toward ∞.
Typing ceil(y) produces the answers 3, 3, 4.
e.g.
>>ceil(11/4)
10 a Ans =
3
fix(x) : Round to the nearest integer toward zero.
The fix () function is used to round the specified values towards zero. Here, fix (A) is used to
round the specified elements of A toward zero which results in an array of integers. The floor
() function is used to round the specified values towards minus infinity.
Y= fix(X) ío"⭲ds cack clcmc⭲t or X to tkc ⭲caícst i⭲tcgcí towaíd zcío. ľkis opcíatio⭲ crrccti:clQ
tí"⭲catcs tkc ⭲"mbcís i⭲ X to i⭲tcgcís bQ ícmo:i⭲g tkc dccimal poítio⭲ or cack ⭲"mbcí:
Course Code: 20EC0454 R20
• Foí positi:c ⭲"mbcís, tkc bcka:ioí or fix is tkc samc as floor.
• Foí ⭲cgati:c ⭲"mbcís, tkc bcka:ioí or fix is tkc samc as ceil.

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.

>>x = -5 - 8i; y = 10 - 5i;


>>mag_product = abs(x*y)
105.4751
>>angle_product = angle(x*y)
angle_ product =
-2.5930
|𝑥|
Similarly, for division, if z = x/y, then |𝑧| = 𝑎𝑛𝑑 ∠𝑧 = ∠𝑥 − ∠𝑦 and
|𝑦|
>> x = (-5-8i); y = 10-5i;
Course Code: 20EC0454 R20
>> mag_division = abs(x/y)

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

How program is designed and developed in MATLAB?


The top-design approach is used to design and develop the program in MTALAB. Top-down
design is the process of starting with a large task and breaking it down into smaller, more easily
understandable pieces (subtasks) which perform a portion of the desired task. Each subtask may in turn
be subdivided into smaller subtasks if necessary. Once the program is divided into small pieces, each
piece can be coded and tested independently.
The steps involved are as follows:
1 a 1. Clearly state the problem that you are trying to solve. Programs are usually written to fill some
perceived need, but that need may not be articulated clearly by the person requesting the program. For
example, a user may ask for a program to solve a system of simultaneous linear equations. he or she
must first know much more about the problem to be solved. Is the system of equations to be solved real
or complex? What is the maximum number of equations and unknowns that the program must handle?
The program designer will have to talk with the user requesting the program, and the two of them will
have to come up with a clear statement of exactly what they are trying to accomplish. A clear statement
of the problem will prevent misunderstandings, and it will also help the program designer to properly
organize his or her thoughts.
Course Code: 20EC0454 R20

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.

Explain Steps for developing a computer solution.


MATLAB is useful for doing numerous complicated calculations and then automatically generating a
plot of the results. The following example illustrates the procedure for developing and testing such a
program.
1. State the problem concisely.
2. Specify the data to be used by the program. This is the input.

3. Specify the information to be generated by the program. This is the output.


4. Work through the solution steps by hand or with a calculator; use a simpler set of data if necessary.
5. Write and run the program.
6. Check the output of the program with your hand solution.
7. Run the program with your input data and perform a “reality check” on the output. Does it make
sense? Estimate the range of the expected result and compare it with your answer.
8. If you will use the program as a general tool in the future, test it by running it for a range of reasonable
2 a
data values; perform a reality check on the results.

Process for developing large program


1. Writing and testing of individual modules (the unit-testing phase).
2. . Writing of the top-level program that uses the modules (the build phase). Not all modules are
included in the initial testing. As the build proceeds, more modules are included.
3. Testing of the first complete program (the alpha release phase). This is usually done only in-
house by technical people closely involved with the program development. There might be
several alpha releases as bugs are discovered and removed.

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.

Explain different types of conditional statements in MATLAB with examples.


A conditional statement is a command that allows MATLAB to make a decision of whether to execute a
group of commands that follow the conditional statement, or to skip these commands. In a conditional
statement, a conditional expression is stated. If the expression is true, a group of commands that follow
3 a
the statement are executed.

if conditional expression consisting of relational and/or logical operators.


Course Code: 20EC0454 R20

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

How switch construct is working in MATLAB?


The switch construct is another form of branching construct. It permits a programmer to select a
particular code block to execute based on the value of a single integer, character, or logical expression.
The general form of a switch construct is
switch (switch_expr)
case case_expr_1
statement 1 Block 1
statement 2
b ...
case case_expr_2
statement 1
statement 2 Block 2

otherwise
statement 1
statement 2 Block 3

end
Course Code: 20EC0454 R20
If the value of switch_expr is equal to case_expr_1, then the first code block will be executed and the
program will jump to the first statement following the end of the switch construct. Similarly, if the value
of switch_expr is equal to case_expr_2, then the second code block will be executed, and the program
will jump to the first statement following the end of the switch construct. The same idea applies for any
other cases in the construct. The otherwise code block is optional. If it is present, it will be executed
whenever the value of switch_expr is outside the range of all of the case selectors. If it is not present and
the value of switch_expr is outside the range of all of the case selectors, then none of the code blocks
will be executed.
Example of a switch construct. The following statements determine whether an integer between 1 and
10 is even or odd and print out an appropriate message. It illustrates the use of a list of values as case
selectors, as well as the use of the otherwise block.
switch (value)
case {1,3,5,7,9}
disp('The value is odd.');
case {2,4,6,8,10}
disp('The value is even.');
otherwise
disp('The value is out of range.');
end

Describe about control-flow structures frequently used in MATLAB programming with


examples.
A control flow subsystem executes one or more times at the current time step when
enabled by a control flow block. There are three basic types of logic, or flow of control,
known as: Sequence logic, or sequential flow. Selection logic, or conditional
flow. Iteration logic, or repetitive flow. MATLAB has several constructs that allow for varying
ways to control the flow of program execution.
1) Iteration:
• while loops
• for loops
2) Selection:
• if - else statements
• if - elseif statements
1) Iteration: Loops allow programmers to execute a sequence of statements more than once. There
are two basic forms of loop constructs: while loops and for loops. The major difference between
the two types of loops is how the repetition is controlled. While loops are usually used when you
do not know how many times you want the loop to execute. It is controlled by a condition. The
for loop is a count controlled loop, i.e., the number of repetitions is known before the loop starts.
WHILE LOOP:
4 a A while loop is a block of statements that are repeated indefinitely as long as some condition is satisfied.
The general form of a while loop is
while expression
...
... Code block
...
end
The controlling expression produces a logical value. If the expression is true, the code block will be
executed, and then control will return to the while statement. If the expression is still true, the statements
will be executed again. This process will be repeated until the expression becomes false. When control
returns to the while statement and the expression is false, the program will execute the first statement
after the end.
Example:
a = 10;
while( a < 20 )
fprintf('value of a: %d\n', a);
a = a + 1;
end

When you run the file, it displays the following result −


Course Code: 20EC0454 R20
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19

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

Compare formatted and binary I/O functions.


Formatted files: Formatted I/O operations produce formatted files. A formatted file contains
recognizable characters, numbers, and so forth. stored as ASCII text. These files are easy to distinguish,
because we can see the characters and numbers in the file when we display them on the screen or print
them on a printer. However, to use data in a formatted file, a MATLAB program must translate the
characters in the file into the internal data format used by the computer. Format conversion specifiers
provide the instructions for this translation. Formatted files have the advantages that we can readily see
what sort of data they contain and it is easy to exchange data between different types of programs using
them.
However, they also have disadvantages. A program must do a good deal of work to convert a number
between the computer’s internal representation and the characters contained in the file. All of this work
is just wasted effort if we are going to be reading the data back into another MATLAB program. Also,
the internal representation of a number usually requires much less space than the corresponding
representation of the number found in a formatted file. For example, the internal representation of a 64-
bit floating-point value requires 8 bytes of space. The character representation of the same value would
be ±d.ddddddddddddddE±ee, which requires 21 bytes of space (one byte per character). Thus, storing
data in character format is inefficient and wasteful of disk space.
Unformatted files (or binary files): Unformatted files (or binary files) overcome these disadvantages
by copying the information from the computer’s memory directly to the disk file with no conversions at
all. Since no conversions occur, no computer time is wasted formatting the data. In MATLAB, binary
a I/O operations are much faster than formatted I/O operations because there is no conversion.
Furthermore, the data occupies a much smaller amount of disk space. On the other hand, unformatted
data cannot be examined and interpreted directly by humans. In addition, it usually cannot be moved
between different types of computers, because different types of computers have different internal ways
5 to represent integers and floating-point values.
Comparison of formatted and Binary files are as follows:

Explain briefly about methods for calling functions.


Methods for Calling Functions
b
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
Course Code: 20EC0454 R20
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;

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])

4. As a string expression:
>>fun1 = ‘x.^2-4’;
>>x = fzero(fun1,[0, 3])
or as
>>x = fzero(‘x.^2-4’,[0, 3])

Describe commonly used commands for plotting graphs in results analysis.


The following are commonly used commands for plotting graphs in results analysis

Examples
Course Code: 20EC0454 R20

Polar Plot

b Write short note on Minimizing a Function of One Variable.


Course Code: 20EC0454 R20
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

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 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.

Figure: Plot function of y = 0.025x5 – 0.0625x4 – 0.333x3 + x2


Its plot is shown in Figure. 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 specified interval does not include it.

Explain about Minimizing a Function of Several Variable.


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.
2 2
For example, to use the function 𝑓 = 𝑥𝑒−𝑥 −𝑦 , first define it in an M- file, using the vector x whose
7 a 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])


Course Code: 20EC0454 R20
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
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.
Write brief note about User defined functions in MATLAB.
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 data output data


Function file

Syntax to create a user-defined function:


function [o1, o2, o3…, on] = func_name (i1, i2, i3, …,im)
Description of the syntax:

4. func_name is the name of our function


5. o1, o2, o3, …, on are the outputs of our function
6. i1, i2, i3, …, im are the inputs of our function
for example, we will create a user-defined function to calculate the area of a circle. We will
b name our function as compute_area, and so our file name will also be compute_area. Below are
the steps to be followed:

5. Initialize the function compute_area


6. Write the logic to compute the area of a circle
7. Save the file by the name compute_area
8. Call this function in the new Matlab window using the name and passing the argument

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

Input 2 (Calling the function):


Compute_area(5)

Output:
Ans = 78.5398

Distinguish between plot and stem in plotting results with an example.


Plot Stem
8 a
plot command is used to create two-dimensional Stem() method in MATLAB is a type of
plots to represent any type of data in a plotting method to represent any type of data
Course Code: 20EC0454 R20
continuous form. The figure has a single curve in a discrete form. This method generates a
with the x values on the abscissa (horizontal axis) plot in the form of vertical lines being
and the y values on the ordinate (vertical axis). extended from the bases line, having little
circles at tips which represents the exact
value of the given data
The curve is constructed of by joining value it does not join the values points with each
points with straight-line segments that connect other to create a continuous graph, it
the points whose coordinates are defined by the emphasizes the fact that the data points are
elements of the vectors x and y. It join the discrete, not continuous.
values points with each other to create a
continuous graph, it emphasizes the fact that
the data points are continuous.
Syntax: Syntax:
Plot(x,y) There are various syntax that are available to
implement stem() method based on a number
where arguments x and y are each a vector (one- of vectors and attributes, used as input
dimensional array). The two vecttors must have argument.
the same number of elements Stem(Y)
Where Y is a data sequence to be presented
in the plot.
Stem(X,Y)
Where X and Y are input vectors and the plot
is generated for Y data points with respect to
the X data point.
Stem(X,Y,a1,a1 value, a2,
a2 value,…..,an ,an value)
Where X and Y are input vectors and an is the
attribute name and an value is the value
corresponding to an attribute.
regr
Example Example
>> x=[1.1 1.8 3.2 5.5 7 7.5 8 10];
>> y=[2 6.5 7 7 5.5 4 6 8];
>> plot(x,y)

How does the subplot function will work in plotting graphs?


subplot command to obtain several smaller “subplots” in the same figure. The syntax is subplot(m,n,p).
This command divides the Figure window into an array of rectangular panes with m rows and n
b columns. The variable p tells MATLAB to place the output of the plot command following the subplot
command into the pth pane. For example, subplot(3,2,5) creates an array of six panes, three panes deep
and two panes across, and directs the next plot to appear in the fifth pane (in the bottom left corner). The
following script file created Figure, which shows the plots of the functions y = e1.2x sin(10x +5) for 0≤ x
≤ 5 and y = |x3 - 100| for -6 ≤ x ≤ 6.
Course Code: 20EC0454 R20
x = 0:0.01:5;
y = exp(-1.2*x).*sin(10*x+5);
subplot(1,2,1) plot(x,y),xlabel(‘x’),ylabel(‘y’),
axis([0 5 -1 1])
x = -6:0.01:6;
y = abs(x.^3-100);
subplot(1,2,2)
plot(x,y),xlabel(‘x’),ylabel(‘y’),axis([-6 6 0 350])
Explain about Exponential and Logarithmic functions.
Exponential function Commands
exp(x) Exponential;
ex
sqrt(x) Square root

Logarithmic function commands


log(x) Natural logarithm ln x
log10(x) Common (base-10) logarithm; log x = log10 x
a
An example is the square root function sqrt. To compute √9, you type sqrt(9) at the command line.
When you press Enter, you see the result ans = 3. You can use functions with variables. For example,
consider the session
>>x = -9; y = sqrt(x)
y
= 0 + 3.0000i

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

c) xlabel(): this label command add x-axis labels


e.g xlabel(‘x’)
it will display ---→t on the x-axis see fig.1
d) ylabel()
e)g ylabel(‘y’)
it will display ---→t on the x-axis see fig.1
10
Explain Three-dimensional plotting functions.
MATLAB provides many functions for creating three-dimensional plots. Here we will summarize the
basic functions to create three types of plots: line plots, surface plots, and contour plots.
Table 1: Three dimensional plotting function

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

Figure1: 3D Line Plots


Surface Mesh Plots:
The function z = f(x, y) represents a surface when plotted on xyz axes, and the mesh function provides
the means to generate a surface plot. Before using this function, generate a grid of points in the xy plane
and then evaluate the function f (x, y) at these points. The meshgrid function generates the grid. Its
syntax is [X,Y] = meshgrid(x,y). If x = xmin:xspacing:xmax and y = ymin:yspacing:ymax, then this
function will generate the coordinates of a rectangular grid with one corner at (xmin, ymin) and the
opposite corner at (xmax, ymax). Each rectangular panel in the grid will have a width equal to xspacing
and a depth equal to yspacing. The resulting matrices X and Y contain the coordinate pairs of every point
in the grid. These pairs are then used to evaluate the function. After the grid is computed, you create the
surface plot with the mesh function. Its syntax is mesh(x,y,z). The grid, label, and text functions can be
used with the mesh function.For example
of the function. This plot appears in Figure 2.
2 2 2 >>[X,Y] = meshgrid(-2:0.1:2);
surface z = 𝑥𝑒[(𝑥−𝑦 ) +𝑦 ],
plot for -2 ≤ x≤2 and >>Z = X.*exp(-((X-Y.^2).^2Y.^2));
>>mesh(X,Y,Z),xlabel(‘x’),ylabel(‘y’),zlabel(‘z’)
-2 ≤ y≤2,
with a spacing of 0.1

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

Surface and contour


Course Code: 20EC0454 R20
combined. created
with the mesh
function and its
variant forms: a)
mesh
b) meshc, c) meshz,
and d) waterfall.

UNIT – V

LINEAR ALGEBRAIC EQUATIONS


a Explain matrix methods for linear equations with example
Sets of linear algebraic equations can be expressed as a single equation, using matrix
notation. This standard and compact form is useful for expressing solutions and for developing
1
software applications with an arbitrary number of variables. In this application, a vector is taken
to be a column vector unless otherwise specified.
Matrix notation enables us to represent multiple equations as a single matrix equation. For
Course Code: 20EC0454 R20
example, consider the following set.
2x1+9x2=7
3x1-4x2=7

This set can be expressed in vector-matrix form as


2 9 𝑥1
[ ] [ ] = [5 ]
3 −4 𝑥2
7
which can be represented in the following compact form
Ax=b --------------- eq(1)
where we have defi ned the following matrices and vectors:
𝑥
A=[2 9 ] 𝑥 = [ 1] 𝑏 = [ 5]
3 −4 𝑥2 7
In general, the set of m equations in n unknowns can be expressed in the form

Equation (1), where A is m x n, x is n x 1, and b is m x 1.


b The following table shows how many hours reactors A and B need to produce 1 ton each of the
chemical products 1, 2, and 3. The two reactors are available for 40 and 30 hr per week,
respectively. Determine how many tons of each product can be produced each week.

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 system is underdetermined. The matrices for the equation Ax = b are


𝑥
5 3 3 40
𝐴= [ ] 𝑏= [ ] 𝑥 = [𝑦]
3 3 4 30 𝑧
Here the rank(A) = rank([A b]) = 2, which is less than the number of unknowns. Thus an infinite number
of solutions exist, and we can determine two of the variables in terms of the third.
Using the rref command rref([A b]), where A = [5,3,3;3,3,4] and b = [40;30], we obtain the following
reduced echelon augmented matrix:
1 0 −0.5 5
[ ]
0 1 1.8333 5

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:

x = 5 + 0.5z ----------------------------------- (3)


y = 5 – 1.8333z ----------------------------- (4)
where z is arbitrary. However, z cannot be completely arbitrary if the solution is to be meaningful. For
example, negative values of the variables have no meaning here; thus we require that x ≥ 0, y ≥ 0 and z ≥
0. Equation (3) y ≥ 0 shows that x ≥ 0 if z ≥ -10. From Equation (4), implies that z ≤ 5/1.8333 = 2.727.
Thus valid solutions are those given by Equations (3) and (4), where 0 ≤ 0z ≤ 2.737 tons. The choice of
z within this range must be made on some other basis, such as pro t.

a Define Rank of Matrix with suitable example.


2 The matrix inverse method will warn us if a unique solution does not exist, but it does not tell us
whether there is no solution or an infinite number of solutions.
Course Code: 20EC0454 R20
In addition, the method is limited to cases where the matrix A is square, that is, cases where the
number of equations equals the number of unknowns. For this reason, we now introduce a
method that allows us to determine easily whether an equation set has a solution and whether it
is unique. The method requires the concept of the rank of a matrix.
For example
3 −4 1
𝐴 = |6 10 2| = 0 ---------------------------eq(1)
9 7 3
If we eliminate one row and one column in the determinant, we are left with a 2 x 2
determinant. Depending on which row and column we choose to eliminate, there are nine
possible 2 x2 determinants we can obtain. These are called sub-determinants. For example, if
we eliminate the second row and third column, we obtain
3 −4
| | = 3(−7) − 9(−4) = 15
9 −7
Subdeterminants are used to define the rank of a matrix.
Definition of Rank:
An m x n matrix A has a rank r ≥1 if and only if |A| contains a nonzero r x r determinant and
every square subdeterminant with r+ 1 or more rows is zero.
For example, the rank of A in Equation (1) is 2 because |A| = 0 while |A| contains at least one
nonzero 2 x 2 subdeterminant.
To determine the rank of a matrix A in MATLAB, type rank(A). If A is n x n, its rank is n if
det(A)≠0. We can use the following test to determine if a solution exists to Ax = b and whether
it is unique. The test requires that we first form the augmented matrix [A b].

b For what values of c will the following set


(a) have a unique solution and
(b) Have an infinite number of solutions? Find the relation between x1 and x2 for these solutions.
6x1 + cx2 = 0
2x1 + 4x2 = 0
a) To find the value of c for which the set of equations will give the unique
solution.
For an m x n matrix A determine rank r ≥1 if and only if |A| contains a
nonzero r x r determinant and every square subdeterminant with r+ 1 or
more rows is zero. To determine the rank of a matrix A in MATLAB,
type rank(A). If A is n x n, its rank is n if det(A)≠0. We can use the
following test to determine if a solution exists to Ax = b and whether it is
unique.
6 𝑐
𝐴=| | = 4(6) − 𝑐(2) = 2𝑐 − 24
2 4
For unique solution determinant of A should be nonzero i.e. det(A)≠0. Therefore c ≠12,
substitute any nonzero value then write x1 in term of x2

(b) c = 12, x1 = -2x2)


a Explain the Reduced Row Echelon Form with an example.
3 We can express some of the unknowns in an underdetermined set as functions of the remaining
unknowns.
Course Code: 20EC0454 R20

Fig.1 A light fixture and its free-body diagram

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.

b Find the system of Linear Equations using Cramer’s Rule


2x + y + z = 3, x – y – z = 0, x + 2y + z = 0
See youtube video https://www.youtube.com/watch?v=axu0GMhhWDY
a Explain Underdetermined Systems with an example.
A System in which number of given equations are less than number of unknown are called
Underdetermined system. An underdetermined system does not contain enough information to determine
4
all the unknown variables, usually but not always because it has fewer equations than unknowns. Thus
an infinite number of solutions can exist, with one or more of the unknowns dependent on the remaining
unknowns.
Course Code: 20EC0454 R20
The left division method works for square and nonsquare 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
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.
In such cases the pseudoinverse method x = pinv(A)*b gives one solution, the minimum norm solution.
In cases where there are an infinite number of solutions, the rref function can be used to express some of
the unknowns in terms of the remaining unknowns, whose values are arbitrary. An equation set can be
underdetermined even though it has as many equations as unknowns. This can happen if some of the
equations are not independent.

Consider the following 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.
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.

inv(A) Computes the inverse of the matrix A.

pinv(A) Computes the pseudo inverse of the matrix


A.

rank(A) Computes the rank of the matrix A.


5
rref([A b]) Computes the reduced row echelon form
corresponding to the augmented matrix [Ab].

x = inv(A)*b Solves the matrix equation Ax _ b using the


matrix inverse.
x = A\b Solves the matrix equation Ax _ b using left
division.
b Write MATLAB script using left division method to solve the following set of equations.
5x1 - 3x2 = 21 7x1 - 2x2 = 36
Left division operator (\) in MATLAB is used to solve sets of linear algebraic equations.
consider the given set to solve such sets in MATLAB we will create two arrays; we will call
Course Code: 20EC0454 R20
them A and B. The array A has as many rows as there are equations and as many columns as
there are variables. The rows of A must contain the coefficients of x1 and x2 in that order. In the
given equation, the first row of A must be 5 and -3; the second row must be 7 and -2; and the
third row must be 2, 8, -9. The array B contains the constants on the right-hand side of the
equation; it has one column and as many rows as there are equations. In the given equations, the
first row of B is 21, the second is 36. The solution is obtained by typing A\B.
The left division method works fine when the equation set has a unique solution.
For given equations
5x1 - 3x2 = 21 & 7x1 - 2x2 = 36

The session script file is as follows


>>A = [5 -3; 7 -1]
>>b=[21; 36]
>>x= A\b
x=

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

Fig.1 Flowchart illustrating a program to solve the linear equations


b Write MATLAB script file to solve following equations
3x1 + 2x2 - 9x3 = - 65
-9x1 - 5x2 + 2x3 = 16
6x1 + 7x2 + 3x3 = 5
Here , Left division operator (\) in MATLAB is used to solve sets of linear algebraic equations.
consider the given set to solve such sets in MATLAB we will create two arrays; we will call
them A and B. The array A has as many rows as there are equations and as many columns as
there are variables. The rows of A must contain the coefficients of x1 , x2 and x3 in that order.
In the given equation, the first row of A must be 3 , 2 and -9; the second row must be -9 , -
5 and 2; and the third row must be 6 , 7 and 3. The array B contains the constants on the
right-hand side of the equation; it has one column and as many rows as there are equations. In
the given equations, the first row of B is -65, the second is 16 and third is 5. The solution is
obtained by typing A\B.
The left division method works fine when the equation set has a unique solution.

>> A=[3 2 -9;-9 -5 2; 6 7 3]


Course Code: 20EC0454 R20
A=

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

𝐽 = ∑(𝑐1𝑥𝑖 + 𝑐2 − 𝑦𝑖)2 = (0𝑐1 + 𝑐2 − 2)2 + (5𝑐1 + 𝑐2 − 6)2 + (10𝑐1 + 𝑐2 − 11)2


𝑖=1
the values of c1 and c2 that minimize J are found by setting the partial derivatives
𝜕𝐽
= 250𝑐1 + 30𝑐2 − 280 = 0
𝜕𝑐1
𝜕𝐽
= 30𝑐1 + 6𝑐2 − 38 = 0
𝜕𝑐2
Course Code: 20EC0454 R20
The solution is c1 = 0.9 and c2 =11/6. The best straight line in the least-squares sense is y = 0.9x + 11/6.

b Write MATLAB script to solve following problem in terms of mg.

If we set mg = 1, the equations have the form AT = b


where
1 −1 1
⎡ ⎤
⎢√35 √34 √42⎥ 𝑇1
⎢ 3 −4 ⎥ 0
𝐴=⎢ 0 𝑇 = [𝑇2] 𝑏 = [0]
⎢√35 √42⎥⎥ 𝑇3 1
⎢ 5 5 5 ⎥
[√35 √34 √42]
The script file to solve this system is

% 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.

a Use the matrix inverse method to solve the following set.


2x1 + 9x2 =5
3x1- 4x2 = 7
The matrix A and the vector b are
2 9 5
A=| | b=| |
3 −4 7

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.

Example : 2x1- 4x2 + 5x3 = – 4


-4x1 - 2x2 + 3x3 = 4
2x1 + 6x2 - 8x3 = 0

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)

A MATLAB session for given equation to check the ranks is


>>A = [2,-4,5;-4,-2,3;2,6,-8];
>>b = [-4;4;0];
>>rank(A)
ans =
2
>>rank([A, b])
ans =
2
>>x = A\b
Warning: Matrix is singular to working precision.
ans =
NaN
NaN
NaN
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. The set is underdetermined because there are fewer than three independent equations; the third
equation can be obtained from the first two. To see this, add the first and second equations, to obtain
-2x1 - 6x2 - 8x3 = 0, which is equivalent to the third equation. Note that we could also tell that the matrix
A is singular because its rank is less than 3. If we use the left division method, MATLAB returns a
message warning that the problem is singular, and it does not produce an answer.

a Rewrite in brief about: 1) Under determined system 2) overdetermined system


1) Under determined system
A System in which number of given equations are less than number of unknown are called
Underdetermined system. An underdetermined system does not contain enough information to determine
all the unknown variables, usually but not always because it has fewer equations than unknowns. Thus
an infinite number of solutions can exist, with one or more of the unknowns dependent on the remaining
unknowns.
Consider the following equations
T1 + T2 + T3 – 400 = 0
9 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
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.

here are three methods to obtain the Transfer function in Matlab:

1. By Using Equation

2. By Using Coefficients

3. By Using Pole Zero gain

Let us consider one example


10𝑠
ℎ(𝑠) =
𝑠2 + 10𝑠 + 25
1. By Using Equation
First, we need to declare ‘s’ is a transfer function then type the whole equation in the command
window or Matlab editor. In this ‘s’ is the transfer function variable.
Command: “tf”
Syntax :
transfer function variable name = tf(‘transfer function variable name’);
Example: consider
10𝑠
ℎ(𝑠) =
𝑠2 + 10𝑠 + 25
Matlab program
>> s=tf(‘s’)
>>h=20*s/(s^2+10*s+25)
h =
10𝑠
𝑠 + 10𝑠 + 25
2
Continuous time transfer function.
2. By Using Coefficients
In this method numerator and denominator, coefficients are used followed by ‘tf’ command.
In the above example
The numerator has only one value which is “10s”, so the coefficient is 10.
And in the denominator there are three terms “, so coefficients are 1, 10 and 25.
Course Code: 20EC0454 R20
Command: “tf”
Syntax:
transfer function variable name = tf([numerator coefficients ] ,[denominator coefficients]
Example: h= tf([10 0],[1 10 25];
Matlab Program
>> h= tf([10 0],[1 10 25];
h =
10𝑠
𝑠 + 10𝑠 + 25
2
Continuous time transfer function
3. By Using Pole Zero gain
In this method, we use the command “zpk”, here z stands for zeros, p stands for poles and k
stands for gain.
Consider
100(𝑠 − 1)(𝑠 + 2)
ℎ=
(𝑠 − 2)(𝑠 − 3)(𝑠 − 4)
In above example :
Zero’s = 1,-2
Pole’s = 2,3,4
Gain = 100
command: zpk

syntax: zpk([zeros],[poles],gain)

example :zpk([1 -2],[2 3 4],100)

Matlab Program

>>h= zpk([1 -2],[2 3 4],100)

h=

100(𝑠 − 1)(𝑠 + 2)
(𝑠 − 2)(𝑠 − 3)(𝑠 − 4)

Continuous-time zero/pole/gain model

>>pzmap(h)

tf(h)

ans =

100 𝑠^2 + 100 𝑠 − 200


𝑠3 − 9 𝑠^2 + 26 𝑠 − 24

a Discuss about computational difficulties using Theoretical Linear Algebra Techniques.


A few of the computational difficulties one might face while attempting to solve some of the linear
10 algebra problems using common theoretical linear algebra methods.
1) Solving a linear system by Cramer's Rule: Cramer's Rule is of significant theoretical and historical
importance. Unfortunately, it cannot be recommended as a practical computational procedure.
Course Code: 20EC0454 R20
Solving a 20 x 20 linear system, even on a fast modern-day computer, might take more than a million
ears to compute the solution with this rule, using the usual definition of the determinant of a matrix.
2) Computing the unique solution of a linear system by matrix inversion: The unique solution
of a nonsingular linear system can be written explicitly as x = A -1b.
Unfortunately, computing a solution to a linear system by explicitly computing the matrix inverse is
not practical. The computation of the matrix inverse is about two-and-a-half times as expensive as
solving the linear system problem itself using a standard elimination procedure and often leads to
more inaccuracies.
Consider a trivial example: Solve 3x = 27. An elimination procedure will give x = 9 and require only one
division. On the other hand, solving the equation using matrix inversion will be cast as x = (l/3) · 27,
giving x = 0.3333 · 27 = 8.999 (in four-digit arithmetic), and will require one division and one
multiplication.
Note that computer time consumed by an algorithm is theoretically measured by the number of
arithmetic operations needed to execute the algorithm.
3) Solving a least-squares problem by normal equations: If the m x n matrix A has full rank,
and m is greater than or equal to n, then the least-squares problem has a unique solution, and this
solution is theoretically given by the solution x to the linear system
AT Ax= AT b
The above equations are known as the normal equations. Unfortunately, this procedure has
some severe numerical limitations. First, in-finite-precision arithmetic, during an explicit
formation of AT A, some vital information might be lost. Second, the normal equations are more
sensitive to perturbations than the ordinary linear system Ax = b, and this sensitivity, in certain
instance, corrupts the accuracy of the computed least-squares solution to an extent not warranted
by the data.
4) Computing the eigenvalues of a matrix by finding the zeros of its characteristic
polynomial: The eigenvalues of a matrix A are the zeros of its characteristic polynomial. Thus
an "obvious" procedure for finding the eigenvalues would be to compute the characteristic
polynomial of A and then find its zeros by a standard well-established root-finding procedure.
Unfortunately, this is not a numerically viable approach. The round-off errors produced during a
process for computing the characteristic polynomial will very likely produce some small
perturbations in the computed coefficients. These small errors in the coefficients can affect the
computed zeros very drastically in certain cases. The zeros of certain polynomials are known to
be extremely sensitive to small perturbations in the coefficients. A classic example of this is the
Wilkinson polynomial. Wilkinson took a polynomial of degree 20 with the distinct roots 1
through 20 and perturbed the coefficient of x19 by a significantly small amount. The zeros of this
slightly perturbed polynomial were then computed by a well-established root-finding procedure.
only to find that some zeros became totally different. Some even became complex.
5) Solving the generalized eigenvalue problem and the quadratic eigenvalue problems by
matrix inversion: The generalized eigenvalue problem in the case where B is nonsingular,
Ax= µBx
is theoretically equivalent to the ordinary eigenvalue problem
B-1Ax= µx
However, if the nonsingular matrix B is sensitive to perturbations, then forming the matrix on
the left-hand side by explicitly computing the inverse of B will lead to inaccuracies that in turn
will lead to computations of inaccurate generalized eigenvalues.
6) Finding the singular values by computing the eigenvalues of ATA: Theoretically. the singular
values of A the nonnegative square roots of the eigenvalues of ATA. However, finding the
singular values this way is not advisable. Again, explicit formation of the matrix product ATA
might lead to the loss of significant relevant information.
Consider a rather trivial example:
1 1
A(𝜖 0)
0 0

where 𝜖 is such that in finite-precision computation l + 𝜖2 = 1. Then computationally we have


ATA = ( 1 1). The eigenvalues now are 2 and 0, So the computed singular values will now be
1 1
given by √2 and 0. The exact singular values, however are √2 and 𝜖/√2.
b Rewrite step by step procedure to solve ordinary differential equation and give one example of
Course Code: 20EC0454 R20
first order linear differential equation.
Step1 : Convert the given differential equation into first order. If it is already first order, no
need to convert it.
Step 2 : Write the function to compute the state derivative.
Step 3 : Use the buit-in function of MatLab used for ordinary differential equation (ode23 or
ode45)
Ste 4: Get the result from the output and interpret it.
Example:
Let us consider the following first order differential equation
𝑑𝑦
=𝑦+𝑡
𝑑𝑡
Or y’ = y+t with the initial condition, y(0)=0
Soluttion:
1. This is the first order differential equation . SO you don’t need to convert it to first
order.
2. Write a function to find the state derivative yprime
function yprime – diffeqn(t,y)
Yprime = y + t
Here diffeqn computes yprime = y+t . Save the function file in C:\matlab\work\
3. Write another script file to use the bilt-in function ode23, the ordinary differential
equation solver. Give the name of the file diffeq1(say)
4. %script file for firtst order equation solution
5. Y(0) = 0
trange =[0:5];
[t,y] = ode23(‘diffeqn’, trange, y0)
plot(t,y)
xlabel(‘t’)
ylabel(‘y’)

You might also like