36
Practical-1 Aim: Introduction to MATLAB MATLAB (matrix laboratory) is a numerical computing environment and fourth-generation programming language. Developed by Math Works, MATLAB allows matrix manipulations, plotting of functions and data, implementation of algorithms, creation of user interfaces, and interfacing with programs written in other languages, including C, C++, Java, and FORTRAN. Since its conception it has developed many advanced features for the manipulation of vectors and matrices. It can solve large systems of equations efficiently and is therefore useful for solving differential equations and optimization problems. It also provides excellent means for data visualization and has symbolic capabilities. MATLAB users come from various backgrounds of engineering, science, and economics. It is widely used in academic and research institutions as well as industrial enterprises. Key Features High-level language for numerical computation, visualization, and application development Interactive environment for iterative exploration, design, and problem solving Mathematical functions for linear algebra, statistics, Fourier analysis, filtering, optimization, numerical integration, and solving ordinary differential equations Built-in graphics for visualizing data and tools for creating custom plots Development tools for improving code quality and maintainability and maximizing performance 1

Introduction to MATLAB

Embed Size (px)

DESCRIPTION

Matlab practical file

Citation preview

Page 1: Introduction to MATLAB

Practical-1

Aim: Introduction to MATLAB

MATLAB (matrix laboratory) is a numerical computing environment and fourth-generation programming language. Developed by Math Works, MATLAB allows matrix manipulations, plotting of functions and data, implementation of algorithms, creation of user interfaces, and interfacing with programs written in other languages, including C, C++, Java, and FORTRAN. Since its conception it has developed many advanced features for the manipulation of vectors and matrices. It can solve large systems of equations efficiently and is therefore useful for solving differential equations and optimization problems. It also provides excellent means for data visualization and has symbolic capabilities. MATLAB users come from various backgrounds of engineering, science, and economics. It is widely used in academic and research institutions as well as industrial enterprises.

Key Features High-level language for numerical computation, visualization, and application

development Interactive environment for iterative exploration, design, and problem solving Mathematical functions for linear algebra, statistics, Fourier analysis, filtering,

optimization, numerical integration, and solving ordinary differential equations Built-in graphics for visualizing data and tools for creating custom plots Development tools for improving code quality and maintainability and maximizing

performance Tools for building applications with custom graphical interfaces Functions for integrating MATLAB based algorithms with external applications and

languages such as C, Java, .NET, and Microsoft ExcelMATLAB involves typing MATLAB code into the Command Window or executing text files containing MATLAB code and functions. Various parts of MATLAB Screen are:

Command WindowYou can enter individual statements in the Command Window. For example, create a variable named a by typing this statement at the command line:

a = 1MATLAB immediately adds variable ‘a’ to the workspace and displays the result in the Command Window.

a = 1

1

Page 2: Introduction to MATLAB

When you do not specify an output variable, MATLAB uses the variable ans, short for answer, to store the results of your calculation.

sin(a)ans =0.8415

The value of ans changes with every command that returns an output value that is not assigned to a variable. You also can enter more than one statement on the same line by separating statements. To distinguish between commands, end each one with a comma or semicolon. Commands that end with a comma display their results, while commands that end with a semicolon do not. To recall previous lines in the Command Window, press the up- and down-arrow keys, (↑ and ↓). Press the arrow keys either at an empty command line or after you type the first few characters of a command.

Current DirectoryThe current directory or folder is a reference location that MATLAB uses to find files. This folder is sometimes referred to as the current directory, current working folder, or present working directory. It is not the same location as the operating system current folder.You can always load files and execute scripts and functions that are in the current folder, even if that folder is not currently on the MATLAB search path. Functions in the current folder take precedence over functions with the same file name that reside anywhere on the search path.

WorkspaceThe MATLAB workspace consists of the variables you create and store in memory during a MATLAB session. You add variables to the workspace by using functions, running MATLAB code, and loading saved workspaces. For example, if you run these statements:

A = magic(4);R = randn(3,4,5);

The workspace includes two variables, A and R.The Workspace browser displays the variables in your workspace. From the Workspace browser, you can select variables to view, modify, or plot.

Command HistoryThe Command History window displays a log of statements you ran in the current and previous MATLAB sessions. The time and date for each session appear at the top of the statements listed for that session, in your operating system's short date format. All entries remain until you delete them, or until the command history file exceeds its maximum size

2

Page 3: Introduction to MATLAB

of 200,000 bytes. When the file exceeds its maximum size, MATLAB automatically deletes the oldest entries. MATLAB saves statements that run in the Command Window to the to the history file. By default, MATLAB automatically saves the command history file after each command. The history file does not include every action taken in MATLAB. For example, modifications of values in the Variable Editor are not included in the Command History.

How to create M file function in MATLAB?Syntax

edit edit file

Description edit opens a new file called Untitled in the Editor. MATLAB does not

automatically save Untitled. edit file opens the specified file in the Editor. If file does not already exist,

MATLAB asks if you want to create it. File can include a partial path, complete path, relative path, or no path. You must have write permission to the path to create file, otherwise, MATLAB ignores the argument.

3

Page 4: Introduction to MATLAB

Practical-2

Aim: List and Describe various basic commands used in MATLAB

a.) SumSyntax: B=sum(A)Returns sums along different dimensions of an array. If A is floating point, that is double or single, B is accumulated natively, that is in the same class as A, and B has the same class as A. If A is not floating point, B is accumulated in double and B has class double.

b.) DiagonalSyntax: diag(A)Where A is a vector with n components, returns an n-by-n diagonal matrix having A as its main diagonal. If A is a square symbolic matrix, diag(A) returns the main diagonal of A.

c.) Sum of diagonal elementsSyntax: sum (diag (A))t adds both the diagonal elements and displays the result. Here, diag(A) is a vector. So, sum(diag(A)) is the sum of vectors. It gives you a simple answer which is scalar.

d.) Flip the elements of matrix from left to rightSyntax: B = fliplr(A)Returns A with columns flipped in the left-right direction, that is, about a vertical axis.

e.) IndexingThe element in row i and column j of A is denoted by A(i,j). For example, A(4,2) is the number in the fourth row and second column. For the magic square, A(4,2) is 15. So to compute the sum of the elements in the fourth column of A, type

A(1,4) + A(2,4) + A(3,4) + A(4,4)

This subscript produces

ans =34

4

Page 5: Introduction to MATLAB

f.) Matrix IndexingIndexing into a matrix is a means of selecting a subset of elements from the matrix.The simple case of a vector and a single subscript. The vector is   v = [16 5 9 4 2 11 7 14];The subscript can be a single value.   v(3)    % Extract the third element   ans = 9The colon notation in MATLAB provides an easy way to extract a range of elements from v.   v(3:7)  % Extract the third through the seventh elements   ans = 9   4   2   11   7

g.) Create an array of all zeroesSyntax: B = zeros(m,n)It returns an m-by-n matrix of zeros.

h.) Create an array of all onesSyntax: B=ones(m,n)It returns an m-by-n matrix of ones.

i.) To calculate mean and standard deviationSyntax: s=std(X)Where X is a vector and s returns the standard deviation.

Syntax: M = mean(A)Returns the mean values of the elements along different dimensions of an array.

j.) Transpose of a matrixSyntax: b = a'It computes the non-conjugate transpose of matrix a and returns the result in b.

k.) To find prime numbersSyntax: p = primes(n)It  returns a row vector containing all the prime numbers less than or equal to n. The data type of p is the same as that of n.

l.) Two-dimensional line plotSyntax: plot(Y)It plots the columns of Y versus the index of each value when Y is a real number. For complex Y, plot(Y) is equivalent toplot(real(Y),imag(Y)).

m.) Factorial of input

5

Page 6: Introduction to MATLAB

Syntax: factorial(n)It returns the product of all positive integers less than or equal to n, where n is a nonnegative integer value. If n is an array, then f contains the factorial of each value of n. The data type and size of f is the same as that of n.

n.) Prime factorSyntax: f=factor(n)It returns a row vector containing the prime factors of n. Vector f is of the same data type as n.

o.) if loopSyntax: if expressionstatements

elseif expressionstatements

elsestatements

end

if expression, statements, end evaluates an expression, and executes a group of statements when the expression is true.

elseif and else are optional, and execute statements only when previous expressions in the if block are false. An if block can include multiple elseif statements.

An evaluated expression is true when the result is nonempty and contains all nonzero elements (logical or real numeric). Otherwise, the expression is false.

p.) while loopSyntax: while expressionstatements

end

while expression, statements, end repeatedly executes one or more MATLAB program statements in a loop as long as an expression remains true.

An evaluated expression is true when the result is nonempty and contains all nonzero elements (logical or real numeric). Otherwise, the expression is false.

6

Page 7: Introduction to MATLAB

Practical-3

Aim: Write a program to implement if condition.

Syntax:

if(condition)

body;

end

Example 1:

x=5;

if(x>3)

disp ( [ ‘x is bigger’ ] );

end

Output:

x is bigger

Example 2:

x=2;

y=3;

z=x+y;

if(z = =5)

disp ( [ ‘result matches’ ] );

end

Output:

result matches

7

Page 8: Introduction to MATLAB

Practical-4

Aim: Write a program to implement if-else condition.

Syntax:

if(condition)

body;

else

body;

end

Example 1:

grade=50;

if(grade>75)

disp( [ ‘congratulation your grade %d is passing \n grade’ ] );

else

disp( [ ‘fail’ ] );

end

Output:

fail

Example 2:

x=2;

y=3;

z=x+y;

if(z = =5)

disp ( [ ‘result matches’ ] );

else

disp ( [ ‘result not matches’ ] );

end

Output:

result matches

8

Page 9: Introduction to MATLAB

Practical-5

Aim: Write a program to implement nested if-else condition.

Syntax:

if(condition)

body;

elseif(condition)

body;

else

body;

end

Example 1:

a=5;

b=10;

c=25;

if(a>b&&a>c)

disp( [ ‘a is greater’ ] );

elseif(b>a&&b>c)

disp( [ ‘b is greater’ ] );

else

disp( [ ‘c is greater’ ] );

end

Output:

c is greater

9

Page 10: Introduction to MATLAB

Practical-6

AIM: Write programs to implement for loop.

FOR LOOP: Syntax of for loop:

for index=values

<program statements>

…………………….

End

Example1:

x=1:5;

for k=1:5

c(k)=x(k)^2;

d(k)=x(k)^3;

e(k)=x(k)^4;

end

OUTPUT: c =

1 4 9 16 25

d=

1 8 27 64 125

e=

1 16 81 256 625

Example2:

for ii=1:3

for jj=1:3

product=ii*jj;

fprintf(“%d*%d=%d\n”,ii,jj,product);

10

Page 11: Introduction to MATLAB

end

end

OUTPUT: 1*1=1

1*2=2

1*3=3

2*1=2

2*2=4

2*3=6

3*1=3

3*2=6

3*3=9

11

Page 12: Introduction to MATLAB

Practical-7

Aim: Write a program to implement while loop.

Syntax:-

While condition do

Body

End_while

While(condition, body)

Example 1 :

Value=input(‘please enter a number between (1-10)’);

Please enter a number between (1-10) 7

While (value<1 || value>10)

Fprintf(‘incorrect input, please try again..!! /n’ )

Disp(value)

Output :

7

Example 2 :

X=3;

While(x<10)

Disp([‘The value of x is’,num2str(x)]);

X=x+1;

End

Output :

The value of x is 3

The value of x is 4

The value of x is 5

The value of x is 6

The value of x is 7

The value of x is 8

The value of x is 9

12

Page 13: Introduction to MATLAB

Practical-8

AIM: write a program to implement switch case.

Syntax: switch switch_expression

Case case_expression

Statements

Case case_expression

Statements

…………………….

Otherwise

Statements

End

Example 1:

Mynumber=input(‘enter the number:’);

Enter the number:1

Switch mynumber

Case 1

Disp(‘negative number’);

Case 2

Disp(‘positive number’);

Case 3

Disp(‘other values’);

Otherwise

Disp(‘invalid input’);

End

Output:

Negative number

13

Page 14: Introduction to MATLAB

Example 2:

Num=input(‘enter the no of day:’);

Enter the no of day:6

Switch num

Case 1

Disp(‘the day is Monday’);

Case 2

Disp(‘the day is Tuesday’);

Case 3

Disp(‘the day is Wednesday’);

Case 4

Disp(‘the day is Thursday’);

Case 5

Disp(‘the day is Friday’);

Case 6

Disp(‘the day is Saturday’);

Case 7

Disp(‘the day is Sunday’);

Otherwise

Disp(‘invalid input’);

end

Output:

The day is saturday

14

Page 15: Introduction to MATLAB

Practical-9

AIM: Write a program to implement function.

Syntax:

function [y1,...,yN] = myfun(x1,...,xM)

Example:

Function y=myfunction(x)

X=1:3;

Y=x.^2+x

Output:

2 6 12

Example:

Function y = average(x)

x=1:4

if ~isvector(x)

error('Input must be a vector')

end

y = sum(x)/length(x);

end

Output:

X= 1 2 3 4 5 6

Ans =

3.5000

15

Page 16: Introduction to MATLAB

Practical-10

Aim: Write a program to demonstrate Array operations.

Arithmetic Operations:In MATLAB arithmetic operation will be preceeded by ‘.’. It shows

array operation. All the operations will be performed element by element.

Operations:

+ element by element addition

- element by element subtraction

* element by element mulatiplication

/ element by element division

^ element by element exponential

Examples:

a=[1 2 3;4 5 6];

b=[1 2 3;1 3 6];

c=a.*b

c =

1 4 9

4 15 36

c=a+b

c =

2 4 6

5 8 12

c=a-b

c =

0 0 0

3 2 0

16

Page 17: Introduction to MATLAB

c=a./b

c =

1.0000 1.0000 1.0000

4.0000 1.6667 1.0000

c=a.\b

c =

1.0000 1.0000 1.0000

0.2500 0.6000 1.0

c=a.^b

c =

1 4 27

4 125 46656

17

Page 18: Introduction to MATLAB

Practical-11

AIM: Introduction with relational operators.

Relational Operations: There are six relational operators:>,<,>=,<=,==,^=.

Examples:

x=[1 3 5;6 7 8];

y=[2 6 7;6 8 9];

z=(x>y)

z =

0 0 0

0 0 0

z=(x<y)

z =

1 1 1

0 1 1

z=(x<=y)

z =

1 1 1

1 1 1

z=(x>=y)

z =

0 0 0

1 0 0

z=(x~=y)

z =

1 1 1

0 1 1

18

Page 19: Introduction to MATLAB

Practical-12

AIM: Introduction with logical operators.

Logical Operations: There are four logical operations:

& logical AND

| logical OR

~ logical NOT

XOR exclusive OR

Examples:

x=[0 5;0 8];

y=[0 3;9 8];

z=(x>y)&(x>4)

z =

0 1

0 0

This operation will return 1 if both conditions are true.

z=x&y

z =

0 1

0 1

z=x|y

z =

0 1

0 1

z=~(x|y)

z =

19

Page 20: Introduction to MATLAB

1 0

0 0

z=xor(x,y)

z =

0 0

0 0

p=[0 9;2 16];

q=sqrt(p)

q =

0 3.0000

0.4142 4.0000

q=exp(p)

q =

1.0e+006 *

0.0000 0.0081

0.0000 8.8861

20

Page 21: Introduction to MATLAB

Practical-13

AIM: Introduction Regarding Usage of Any Network Simulator.

Virtual Box is a cross-platform virtualization application. What does that mean? For one thing, it installs

on your existing Intel or AMD-based computers, whether they are running Windows, Mac, Linux or

Solaris operating systems. Secondly, it extends the capabilities of your existing computer so that it can run

multiple operating systems (inside multiple virtual machines) at the same time. So, for example, you can

run Windows and Linux on your Mac, run Windows Server 2008 on your Linux server, run Linux on your

Windows PC, and so on, all alongside your existing applications. You can install and run as many virtual

machines as you like -- the only practical limits are disk space and memory.

VirtualBox is deceptively simple yet also very powerful. It can run everywhere from small embedded

systems or desktop class machines all the way up to datacenter deployments and even Cloud

environments.

The following screenshot shows you how VirtualBox, installed on a Mac computer, is running Windows 7

in a virtual machine window:

21

Page 22: Introduction to MATLAB

Why is virtualization useful?

The techniques and features that VirtualBox provides are useful for several scenarios:

Running multiple operating systems simultaneously. VirtualBox allows you to run more

than one operating system at a time. This way, you can run software written for one operating

system on another (for example, Windows software on Linux or a Mac) without having to reboot

to use it. Since you can configure what kinds of "virtual" hardware should be presented to each

such operating system, you can install an old operating system such as DOS or OS/2 even if your

real computer's hardware is no longer supported by that operating system.

Easier software installations. Software vendors can use virtual machines to ship entire

software configurations. For example, installing a complete mail server solution on a real machine

can be a tedious task. With VirtualBox, such a complex setup (then often called an "appliance")

can be packed into a virtual machine. Installing and running a mail server becomes as easy as

importing such an appliance into VirtualBox.

Testing and disaster recovery. Once installed, a virtual machine and its virtual hard disks can

be considered a "container" that can be arbitrarily frozen, woken up, copied, backed up, and

transported between hosts.

On top of that, with the use of another VirtualBox feature called "snapshots", one can save a

particular state of a virtual machine and revert back to that state, if necessary. This way, one can freely

experiment with a computing environment. If something goes wrong (e.g. after installing misbehaving

software or infecting the guest with a virus), one can easily switch back to a previous snapshot and avoid

the need of frequent backups and restores.

Any number of snapshots can be created, allowing you to travel back and forward in virtual machine time.

You can delete snapshots while a VM is running to reclaim disk space.

Infrastructure consolidation. Virtualization can significantly reduce hardware and electricity

costs. Most of the time, computers today only use a fraction of their potential power and run with

22

Page 23: Introduction to MATLAB

low average system loads. A lot of hardware resources as well as electricity is thereby wasted. So,

instead of running many such physical computers that are only partially used, one can pack many

virtual machines onto a few powerful hosts and balance the loads between them.

Features overview

Here's a brief outline of VirtualBox's main features:

Portability. VirtualBox runs on a large number of 32-bit and 64-bit host operating systems (again,

see  VirtualBox is a so-called "hosted" hypervisor (sometimes referred to as a "type 2" hypervisor).

Whereas a "bare-metal" or "type 1" hypervisor would run directly on the hardware, VirtualBox

requires an existing operating system to be installed. It can thus run alongside existing applications

on that host.

To a very large degree, VirtualBox is functionally identical on all of the host platforms, and the same file

and image formats are used. This allows you to run virtual machines created on one host on another host

with a different host operating system; for example, you can create a virtual machine on Windows and

then run it under Linux.

In addition, virtual machines can easily be imported and exported using the Open Virtualization Format

(OVF), an industry standard created for this purpose. You can even import OVFs that were created with a

different virtualization software.

No hardware virtualization required. For many scenarios, VirtualBox does not require the

processor features built into newer hardware like Intel VT-x or AMD-V. As opposed to many

other virtualization solutions, you can therefore use VirtualBox even on older hardware where

these features are not present. The technical details are explained in ”.

Guest Additions: shared folders, seamless windows, 3D virtualization. The

VirtualBox Guest Additions are software packages which can be installed inside of supported

guest systems to improve their performance and to provide additional integration and

23

Page 24: Introduction to MATLAB

communication with the host system. After installing the Guest Additions, a virtual machine will

support automatic adjustment of video resolutions, seamless windows, accelerated 3D graphics and

more. In particular, Guest Additions provide for "shared folders", which let you access files from

the host system from within a guest machine.

Multigeneration branched snapshots. Virtual Box can save arbitrary snapshots of the state

of the virtual machine. You can go back in time and revert the virtual machine to any such

snapshot and start an alternative VM configuration from there, effectively creating a whole

snapshot tree. For. You can create and delete snapshots while the virtual machine is running.

VM groups. Virtual Box provides a groups feature that enables the user to organize virtual

machines collectively, as well as individually. In addition to basic groups, it is also possible for

any VM to be in more than one group, and for groups to be nested in a hierarchy -- i.e. groups of

groups. In general, the operations that can be performed on groups are the same as those that can

be applied to individual VMs i.e. Start, Pause, Reset, Close (Save state, Send Shutdown,

Poweroff), Discard Saved State, Show in fileSystem, Sort.

Clean architecture; unprecedented modularity. VirtualBox has an extremely modular

design with well-defined internal programming interfaces and a clean separation of client and

server code. This makes it easy to control it from several interfaces at once: for example, you can

start a VM simply by clicking on a button in the VirtualBox graphical user interface and then

control that machine from the command line, or even remotely. Due to its modular architecture,

VirtualBox can also expose its full functionality and configurability through a

comprehensive software development kit (SDK), which allows for integrating every aspect of

VirtualBox with other software systems.

Remote machine display. The VirtualBox Remote Desktop Extension (VRDE) allows for high-

performance remote access to any running virtual machine. This extension supports the Remote

Desktop Protocol (RDP) originally built into Microsoft Windows, with special additions for full

client USB support.

The VRDE does not rely on the RDP server that is built into Microsoft Windows; instead, it is plugged

directly into the virtualization layer. As a result, it works with guest operating systems other than

Windows (even in text mode) and does not require application support in the virtual machine either.

24

Page 25: Introduction to MATLAB

Starting VirtualBox

After installation, you can start VirtualBox as follows:

On a Windows host, in the standard "Programs" menu, click on the item in the "VirtualBox"

group. On Vista or Windows 7, you can also type "VirtualBox" in the search box of the

"Start" menu.

On a Mac OS X host, in the Finder, double-click on the "VirtualBox" item in the

"Applications" folder. (You may want to drag this item onto your Dock.)

On a Linux or Solaris host, depending on your desktop environment, a "VirtualBox" item

may have been placed in either the "System" or "System Tools" group of your "Applications"

menu. Alternatively, you can type VirtualBox in a terminal.

When you start VirtualBox for the first time, a window like the following should come up:

This window is called the "VirtualBox

Manager". On the left, you can see a pane

that will later list all your virtual machines.

Since you have not created any, the list

is empty. A row of buttons above it

allows you to create new VMs and work on

existing VMs, once you have some. The pane

on the right displays the properties of the

virtual machine currently selected, if any.

Again, since you don't have any machines

yet, the pane displays a welcome message.

25

Page 26: Introduction to MATLAB

To give you an idea what Virtual Box might look like later, after you have created many machines, here's

another example:

26