00 mi piace00 non mi piace

212 visualizzazioni50 pagineApr 10, 2011

© Attribution Non-Commercial (BY-NC)

DOC, PDF, TXT o leggi online da Scribd

Attribution Non-Commercial (BY-NC)

212 visualizzazioni

00 mi piace00 non mi piace

Attribution Non-Commercial (BY-NC)

Sei sulla pagina 1di 50

Ex. No.:

Date:

MATLAB BASICS

AIM:

To study the basics about the matlab environment.

INTRODUCTION:

• The name MATLAB stands for MATrix LABoratory, because its basic data element

is a matrix(array).

• MATLAB can be used in math computation, modeling, and simulation , data analysis

MATLAB WINDOWS:

Window Purpose

Command Window Main window enters variable, runs program.

Figure Window Contains output from graphic commands.

Editor Window Create and debugs scripts and function files.

Help Window Provide help information.

Provides access to tools, demos, and

Launch Window

documentation.

Logs commands entered in the command

Command History Window

window.

Provide information about the variables that

Workspace Window

are used.

Current Directory Window Show that files in the current directory.

Command Outcome

Clear Removes all variable from the memory.

Removes only variables x, y and z from the

Clear x y z

memory.

Displays a list of variables currently in the

Who

memory.

Whos Displays a list of the variable currently in the

memory and their size together with

Register Number: 10805057 Name: Mithun Mohandas

• All variables in Matlab are arrays. A scalar is an array with one element, a

vector is an array with one row, or one column, of elements, and a matrix is an array with

elements in rows and columns.

• For example a=1; means assign a value of 1 to a scalar ‘a’. The variable is

defined by the input when the variables is assigned. There is no need to define the size of the

array before the elements are assigned.

• When a command is typed in the command window and the Enter key is

pressed, the command is executed. Any output that the command generates is displayed in the

command window. If a semicolon (;) is typed at the end of a command the output of the

command is not displayed.

Example:

>>a=1;

>>b=2

b =

2

>>who

Your variables are:

ab

>> whos

Name Size Bytes Class

a 1x1 8 double array

b 1x1 8 double array

Grand total is 2 element using 16 bytes

Register Number: 10805057 Name: Mithun Mohandas

B =

Matlab is easy

The matlab working environment contains several layouts. The programmer can

select their own layout and can open any needed window from the menus. And all the files

will be saved in the current directory as default.

Register Number: 10805057 Name: Mithun Mohandas

RESULT:

Thus all the matlab basic commands were executed successfully and the results

were obtained.

Ex. No.: OPERATORS AND BUILT-IN FUNCTIONS IN

Date: MATLAB

AIM:

To study all the operators available in matlab (like arithmetic, relational, logical) and

built-in math functions.

OPERATORS IN MATLAB:

I) ARITHMETIC OPERATORS

I) ARITHMETIC OPERATORS:

Addition + 5+5

Subtraction - 5-3

Multiplication * 5*3

Right Division / 5/3

Left Division \ 5\3=3\5

Exponentiation ^ 5^3

Example:

>>a=5

a =5

>>b=3

Register Number: 10805057 Name: Mithun Mohandas

b=3

>>c=a+b

C=8

>>c=a-b

c=2

>>c=a*b

c=15

>>c=a/b

c=1.6667

>>c=a\b

c=0.6000

>>c=a^b

c=125

Function Description

sqrt(x) Square root

exp(x) Exponential

abs(x) Absolute value

Natural logrithm

log(x)

Base e logrithm(ln)

log10(x) Base 10 logrithm

The factorial function x!

factorial(x)

(x must be a positive integer.)

sin(x) Sine of angle x (x is radians)

cos(x) Cosine of angle x (x is radians)

tan(x) tangent of x (x is radians)

cot(x) cotangent of x (x is radians)

Example:

>>sqrt(4)

ans=2

>>exp(5)

ans=148.4132

>>abs(-24)

ans=24

>>log=(1000)

Register Number: 10805057 Name: Mithun Mohandas

ans=6.9078

>>log10(1000)

ans=3.0000

>>factorial(5)

ans=120

>>sin(pi/6)

ans=0.5000

>>cos(pi/6)

ans=0.8660

>>tan(pi/6)

ans=0.5774

>>cot(pi/6)

ans=1.7321

< Less than

> Greater than

<= Less than or equal to

>= Greater than or equal to

== Equal to

Example:

>>5>8

ans=0

>>a=5<10

a=1

>>y=(6<10)+(7>8)+(5*3==60/4)

y=2

>>b=[15 6 9 4 11 7 14]; c=[8 20 9 2 19 7 10];

>>d=c>=b

D=0 1 1 0 1 1 0

>>b==c

ans=0 0 1 0 0 1 0

>>b~=c

Register Number: 10805057 Name: Mithun Mohandas

ans=1 1 0 1 1 0 1

>>f=b-c>0

f=1 0 0 1 0 0 1

>>a=[2 9 4; -3 5 2; 6 7 -1]

A= 2 9 4

-3 5 2

6 7 -1

>>B=A<=2

B= 1 0 0

1 0 1

0 0 1

Function Description

round(x) round to nearest integer

fix(x) Round towards zero

ceil(x) Round towards possitive infinity

floor(x) Round towards negetive infinity

rem(x, y) Returs the reminder after x is devided by y.

Signum function, Return 1 if x>0, -1ifx<0,

sign(x)

and 0 ifx=0

Example:

>>round(17/5)

ans=3

>>fix(13/5)

ans=2

>>ceil(11/5)

ans=3

>>floor(-9/4)

ans=-3

>>rem=13,5)

Register Number: 10805057 Name: Mithun Mohandas

ans=3

>>sign(5)

ans=1

RESULT:

Thus all the matlab basic commands using arithmetic, relational, logical and built-

in math functions were executed successfully and the results were obtained.

Ex. No.:

Date:

SCRIPT FILES IN MATLAB- AN INTRODUCTION

• Basically the first part of the program will be the description of the program

commanded using the command symbol % as the first character of the line. You

can add any number of command lines as we need.

• When a script file runs, MATLAB will execute the commands in the order they

are written just as if they were type in Command Window. To run a script file you

have to click the run icon in the editor window.

• When a script file has a command that generates the output (ex- assignment of a

value of a variable with out semicolon at the end) the output display in the

Command Window.

• To open a new script file go to file menu, select NEW, and then select the M-

FILE

Go to File->new->M file

And the new M file will be displayed in the editor window as follows.

Register Number: 10805057 Name: Mithun Mohandas

RESULT:

Ex. No.:

Date:

IF-ELSE LOOP- WORKERS PAY

AIM: Write a Matlab script to calculate the pay (salary) of the worker .

ALGORITHM:

Step 1: Get the hours worked and value of wage for 1 hour.

Step 2: Calculate the wage using the formula pay=pay+((t-40)*0.5*h)

Step 3: Print the output

CODE: (workerspay.m)

t=input('enter the value of hours worked');

h=input('enter the value of hourly wage');

pay=t*h;

if t>40

pay=pay+((t-40)*0.5*h);

Register Number: 10805057 Name: Mithun Mohandas

else

pay=t*h+(50/100*h*(t-40));

disp (' the wage of the worker is',pay);

end

OUTPUT:

enter the value of hourly wage 45

pay =17910

RESULT:

Thus the matlab script to calculate the employee’s salary wage was executed

successfully.

Ex. No.:

Date:

IF-ELSE LOOP- FAHRENHEIT TO CELCIUS

AIM:

Write a script that asks for a temperature (in degrees Fahrenheit) and computes

the equivalent temperature in degrees Celcius. The script should keep running

Until no number is provided to convert. [NB. The function isempty will be useful]

ALGORITHM:

Step 1: Get the temperature in fahrenheit

Step 2: Convert Fahrenheit to celcius using the formula C = 5*(F – 32)/9

Step 3: Print the Celcius value

CODE:

TinF = input(‘Temperature in F: ‘); % get input

if isempty(TinF) % how to get out

break

Register Number: 10805057 Name: Mithun Mohandas

end

TinC = 5*(TinF – 32)/9; % conversion

disp(‘ ‘)

disp([‘ Temperature in C = ‘,num2str(TinC)])

disp(‘ ‘)

end

OUTPUT:

Temperature in F: 200

Temperature in C = 93.3333

RESULT:

Thus the matlab script to convert Fahrenheit to celcius was executed successfully.

Ex. No.:

Date:

FOR END LOOP- SUM OF FIRST N NUMBERS

AIM:

Write a script using for end loop to calculate the sum of the first n real numbers.

ALGORITHM:

Step 1: Get the N value

Step 2: using for end loop calculate the sum of 1 to N numbers

Step 3: Print the sum value

CODE:

%the script file to calculating the sum of the real number

n=input('enter the value of n');

sum=0;

for k=1:1:n

sum=sum+k

end

Register Number: 10805057 Name: Mithun Mohandas

OUTPUT:

sum =1

sum =3

the sum of n number is 3.00000

RESULT:

Thus the matlab script to calculate the sum of the first n real numbers was executed

successfully.

Ex. No.:

Date:

FOR END LOOP- SUM OF DIGITS

AIM:

Write down the MATLAB expressions that will correctly compute the following:

Given the vector x = [1 8 3 9 0 1], create a short set of commands that will

b. Computes the running sum

(for element j, the running sum is the sum of the

elements from 1 to j, inclusive. Check with cumsum.)

c. computes the sine of the given x-values (should be a vector)

CODE:

x = [1 8 3 9 0 1]

a. total = 0;

for j = 1:length(x)

Register Number: 10805057 Name: Mithun Mohandas

end

b. runningTotal = zeros(size(x));

runningTotal(1) = x(1);

for j = 2:length(x)

runningTotal(j) = runningTotal(j-1) + x(j);

end

c. s = zeros(size(x));

for j = 1:length(x)

s(j) = sin(x(j));

end

RESULT:

Thus the given expressions were written as a matlab script files and executed

successfully.

Ex. No.:

Date:

FOR END LOOP- ARRAY MANIPULATION

AIM:

Create an M-by-N array of random numbers (use rand). Move through the

array, element by element, and set any value that is less than 0.2 to 0 and any

value that is greater than (or equal to) 0.2 to 1.

CODE:

A = rand(4,7);

[M,N] = size(A);

for j = 1:M

for k = 1:N

if A(j,k) < 0.2

A(j,k) = 0;

else

A(j,k) = 1;

Register Number: 10805057 Name: Mithun Mohandas

end

end

end

RESULT:

Thus the given manipulation with arrays using for end loop was executed

successfully

Ex. No.:

Date:

SIMPLE INTEREST AND COMPOUND INTEREST

AIM: Write a Matlab script to calculate the Simple interest and Compound interest

ALGORITHM:

Step 1: Get the Principal amount, rate of interest and the period (in number of years)

Step 2: Calculate the simple interest and compound interest using the formula

ci=p*(1+r/100)^t and si=p*r*t/100.

Step 3: Print the output

CODE: (simplecompound.m)

p=input('enter the value of principle');

r=input('enter the value of rate');

t=input ('enter the value of year');

ci=p*(1+r/100)^t;

Register Number: 10805057 Name: Mithun Mohandas

si=p*r*t/100;

display('the ci is');

display(ci);

display('the si is');

display(si);

OUTPUT:

enter the value of rate10

enter the value of year5

the ci is

ci = 1.6105e+003

the si is

si = 500

RESULT:

Thus the matlab script to calculate the simple and compound interest was executed

successfully and the results were obtained.

Ex. No.: MANIPULATION WITH ARRAY

Date: SINGLE DIMENSION

AIM: To study all the built in functions for the manipulation with the single dimensional

arrays.

If A is a vector,

return the mean >>A=[5 9 2 4];

mean(A) value of the >>mean(A)

element of the ans=5

vector.

Register Number: 10805057 Name: Mithun Mohandas

If A is the vector,

C is the largest >>A=[5 9 2 4 11 6 7 11 0 1];

c=max(A) element in A. If A >>C=max(A)

is a matrix , C is a C=11

row vector >>[d,n]=max(A)

containing the d=11

largest element of n=5

each column of A.

>>[d,n]=max(A) [d,n]=max(A) in A. N is the position of the element

d=11 (the first if several have the max

n=5 value).

max(A), but for

min(A) >>A=[5 9 2 4];

the smallest

element.

The same as

[d,n]=max(A), but >>min(A)

[d,n]=min(A)

for the smallest ans=2

element.

if A the vector ,

>>A=[5 9 2 4];

arranges the

sum(A) >>sum(A)

elements of the

ans=20

vector.

If A is the vector,

arranges the >>A=[5 9 2 4];

sort(A) elements of the >>sort(A)

vector in ans=2 4 5 9

ascending order.

If A the vector, returns the >>A=[5 9 2 4];

median(A) median value of the >>median(A)

elements of the vectors. ans=4.5000

If A is a vector, return the >>A=[5 9 2 4];

std(A) standard deviation of the >>std(A)

elements of the vectors ans=2.9439

>>A=[5 9 2 4];

Returns the determinant of

det(A) det(A)

a square matrix A

ans=-2

Calculates the scaler (dot)

>>a=[1 2 3];

product of two vectors a

>>b=[2 4 1];

dot(a,b) and b. The vectors can

>>dot(a,b)

each be row or column

ans=26

vectors.

Register Number: 10805057 Name: Mithun Mohandas

>>a=[1 2 3];

of two product of two

>>b=[2 4 1];

cross(a,b) vectors a and b, (axib). The

>>cross(a,b)

two vectors must have 3

ans= -5 3 -2

elements.

>>A=[2 -2 1;3 2 -1;2 -3 2];

>>inv(A)

Returns the inverse of a ans=

inv(A)

square matrix A. 0.2000 0.2000 0

-1.6000 0.4000 1.0000

-2.6000 0.4000 2.0000

RESULT:

Thus all the built in functions for the manipulation with one dimensional array were

executed successfully and the results were obtained.

Ex. No.: MANIPULATION WITH ARRAY

Date: SINGLE DIMENSION

AIM: To study all the manipulation with the single dimensional arrays.

COMMANDS:

Creating a vector (single row with any number of columns)

>>X=[1 2 3 4 5]

X =

1 2 3 4 5

Addressing the elements of a vector

Register Number: 10805057 Name: Mithun Mohandas

>>X=[1 2 3 4 5]

>>X(3)

Ans =

3

Adding the elements of a vector by addressing the index value

>>X(1)+X(3)

Ans =

4

Creating a new vector from an existing vector

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

>>Y=X(3:7)

Y=

3 4 5 6 7

Creating a new vector from an existing vector by specifying some part of the elements

from the old vector, and add new elements at the end of the new vector(But the limit of

your new vector should be equal to the size of the old vector).

>>A=1:1:10

A =

1 2 3 4 5 6 7 8 9 10

>>B=A([3,5, 7:10])

3 5 7 8 9 10

>> B=A([3:6, 7:10])

B = 3 4 5 6 7 8 9 10

Creating a new vector with constant spacing

>>X=1:10

X=

1 2 3 4 5 6 7 8 9 10

Creating a vector with constant spacing by specifying the first term, the spacing, and

the last term

>>X=[1:2:13]

X=

1 3 5 7 9 11 13

Register Number: 10805057 Name: Mithun Mohandas

Creating a vector with constant spacing by specifying the first term and the last term

and the number of terms:

>>X= linspace(0,8,6)

X=

0 1.6000 3.2000 4.8000 6.4000 8.0000

>> X=[[1:1:3];[1:1:3];[1:1:3]]

X=

1 2 3

1 2 3

1 2 3

X=[linspace(1,4,3);linspace(2,8,3);linspace(5,10,3)]

X =

1.0000 2.5000 4.0000

2.0000 5.0000 8.0000

5.0000 7.5000 10.0000

RESULT:

Thus all the basic manipulation with one dimensional array were executed

successfully and the results were obtained.

Ex. No.: MANIPULATION WITH TWO DIMENSIONAL

Date: ARRAY- MATRIX OPERATIONS

AIM: To create a two dimensional array and perform all the matrix operations like matrix

addition, subtraction and multiplication.

DESCRIPTION:

Register Number: 10805057 Name: Mithun Mohandas

and columns. Matrices can be used to store information like in a table. Matrices play an

important role in linear algebra and are used in science and engineering to describe many

physical quantities. and all the possible matrix operations using element by element operator.

Creating a two dimensional array with all the elements are equal to 0

>>A=zeros(3,4)

0 0 0 0

0 0 0 0

0 0 0 0

Creating a two dimensional array with all the elements are equal to 1(unit matrix)

A=ones(4,3)

A =

1 1 1

1 1 1

1 1 1

1 1 1

Creating a two dimensional array with all the diagonal elements are equal to 1

>>A=eye(3)

A =

1 0 0

0 1 0

0 0 1

Note: 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. That matrix is called the

identity matrix.

MATRIX ADDITION:

>>B=[1 2 3

456

7 8 9] ;

Register Number: 10805057 Name: Mithun Mohandas

>>C=A+B

C=

2 4 6

8 10 12

14 6 18

MATRIX SUBSTRACTION:

>>C=A-B

0 0 0

0 0 0

0 0 0

MATRIX MULTIPLICATION:

Note: For to perform matrix multiplication the number of columns of the first matrix should

be equal to the number of rows of the second matrix.

>>C=A*B

30 36 42

66 81 96

102 126 150

MATRIX TRANSPOSE

>>A=[1 2;3 4]

>>B=A’

B= 1 3

24

>>A =

1 2 3

4 5 6

7 8 9

>>size(A)

Register Number: 10805057 Name: Mithun Mohandas

3 3

Finding the diagonal elements of the array

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

>>A =

1 2 3

4 5 6

7 8 9

>>B=diag(A)

>>B =

1 0 0

0 5 0

0 8 0

For a vector:

A(:) Refers to all the elements of the vector A (either a row or a column vector)

A(m:n) Refers to elements m through n of the vector A.

For example:

>>A=[1 2 3 4 5];

>>B=A(2:4)

B =

2 3 4 here a vector B is created from the elements 2 through 4 of vector A.

For a matrix

A(:,n) Refers to the elements in all the rows of column n of the matrix A.

A(n,:) Refers to the elements in all the columns of row n of the matrix A.

A(:,m:n) Refers to the elements in all the rows between columns m and n of the matrix A.

A(m:n,:) Refers to the elements in all the columns between rows m and n of the matrix A.

A(m:n,p:q) Refers to the elements in rows m through n and columns p through q of the

matrix A.

Register Number: 10805057 Name: Mithun Mohandas

>>A =

1 2 3

4 5 6

7 8 9

>>B=A(:,3)

B=

7 8 9

>>C=A(2,:)

4 5 6

E=A(1:2,:)

1 2 3

4 5 6

RESULT:

Thus all the basic manipulation with two dimensional array were executed

successfully and the results were obtained.

Ex. No.:

Date:

SOLVING MATHEMATICAL EXPRESSIONS - I

xn = (-1)n+1/(2n-1)

Add up the elements of the version of this vector that has 100 elements.

CODE :

Register Number: 10805057 Name: Mithun Mohandas

n = 1:100;

Y=sum(X)

OUTPUT:

Y=

0.7829

RESULT:

Thus the given mathematical expression was executed successfully and the results

were obtained.

Ex. No.:

Date:

SOLVING MATHEMATICAL EXPRESSIONS - II

AIM:

Write down the MATLAB expressions that will correctly compute the following:

a. ln(2 + t + t2)

b. et(1 + cos(3t))

c. cos2(t) + sin2(t)

Register Number: 10805057 Name: Mithun Mohandas

e. cot(t)

f. sec2(t) + cot(t) - 1

Test that your solution works for t = 1:0.2:2

CODE:

>>t = 1:0.2:2

a. >>log(2 + t + t.^2)

b. >>exp(t).*(1 + cos(3*t))

c. >>cos(t).^2 + sin(t).^2 (all ones!)

d. >>atan(t)

e. >>cot(t)

f. >>sec(t).^2 + cot(t) – 1

RESULT:

Thus the given mathematical expression was executed successfully and the results

were obtained.

Ex. No.:

Date:

SOLVING MATHEMATICAL EXPRESSIONS - III

Register Number: 10805057 Name: Mithun Mohandas

AIM:

Write down the MATLAB expressions that will correctly compute the following:

>> randn('seed',123456789)

>> F = randn(5,10);

a. Compute the mean of each column and assign the results to the elements of a

vector called avg.

b. Compute the standard deviation of each column and assign the results to the

elements of a vector called s.

c. Compute the vector of t-scores that test the hypothesis that the mean of each

Column is no different from zero.

d. If Pr(|t| > 2.132 ) = 0.1 with 4 degrees of freedom, are any of the mean values

in the vector avg statistically different from 0?

CODE:

randn('seed',123456789)

F = randn(5,10);

N = size(F,1)

avg = mean(F)

s = std(F)

tscore = (avg - 0)./(s/sqrt(N))

OUTPUT:

N=

5

avg =

Columns 1 through 5

1.0265 -0.0674 -0.2153 -0.1415 -0.3151

Columns 6 through 10

0.3403 -0.6386 -0.3431 0.1726 0.3760

s=

Columns 1 through 4

1.2131 0.7533 0.3313 0.5499

Register Number: 10805057 Name: Mithun Mohandas

Columns 5 through 8

0.7748 0.9208 1.1053 1.0867

Columns 9 through 10

0.6738 0.9204

tscore =

Columns 1 through 4

1.8922 -0.1999 -1.4533 -0.5754

Columns 5 through 8

-0.9093 0.8263 -1.2918 -0.7060

Columns 9 through 10

0.5729 0.9134

Register Number: 10805057 Name: Mithun Mohandas

RESULT:

Thus the given mathematical expression was executed successfully and the results

were obtained.

Ex. No.:

Date:

SOLVING MATHEMATICAL EXPRESSIONS - IV

AIM:

Write down the MATLAB expressions that will correctly compute the following:

b. assign the last 2 rows of A to an array called y

c. compute the sum over the columns of A

d. compute the sum over the rows of A

e. compute the standard error of the mean of each column of A (NB. the standard

error of the mean is defined as the standard deviation divided by the

square root of the number of elements used to compute the mean.)

CODE:

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

x1 = A(1,:)

y = A(end-1:end,:)

c = sum(A)

d = sum(A,2)

N = size(A,1), e = std(A)/sqrt(N)

OUTPUT:

A= 2 4 1

6 7 2

3 5 9

x1 =2 4 1

y=6 7 2

Register Number: 10805057 Name: Mithun Mohandas

3 5 9

c =11 16 12

d= 7

15

1

N =3

e =1.2019 0.8819 2.5166

>> d = sum(A,2)

d =7

15

17

Register Number: 10805057 Name: Mithun Mohandas

RESULT:

Thus the given mathematical expression was executed successfully and the results

were obtained.

Ex. No.:

Date:

SOLVING MATHEMATICAL EXPRESSIONS - V

AIM:

Write down the MATLAB expressions that will correctly compute the following:

b. assign the odd-numbered rows to an array called C

c. convert A into a 4-by-3 array

d. compute the reciprocal of each element of A

e. compute the square-root of each element of A

CODE:

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

B = A(:,2:2:end)

C = A(1:2:end,:)

c = reshape(A,4,3)

OUTPUT-

A=

2 7 9 7

3 1 5 6

8 1 2 5

B=

Register Number: 10805057 Name: Mithun Mohandas

7 7

1 6

1 5

C=2 7 9 7

8 1 2 5

C= 2 1 2

3 1 7

8 9 6

7 5 5

Register Number: 10805057 Name: Mithun Mohandas

RESULT:

Thus the given mathematical expression was executed successfully and the results

were obtained.

Ex. No.:

PLOT FORMATION

Date:

• It includes specifying axis lables , plot title, legend, grid, range of custom

axis and text lables.

• Plots can be formatted by using MATLAB command that are follow the

PLOT or FPLOT commands.

computer program(script file).

The formatting commands are entered after the PLOT or the FPOT commands

Labels can be placed next to the X-LABEL and Y-LABEL commands

which have the from:-

X-LABEL(‘text as string’)

Y-LABEL(‘text as string’)

title(‘text as string’)

Register Number: 10805057 Name: Mithun Mohandas

A text label can be placed in the plot with the TEXT or GTEXT

commands:-

gtext(‘text as string’)

• The LEGEND command places a legend on the plot.

• The legend shows a sample of the line type of each graph that is plotted,

and places a lebels, spcified by the user, beside the line sample.

Legend(‘string1’,’string2’, ......,pos)

• The string are the labelsthat are placed next to the line sample.

• That order corresponds to the order that the graphs were created.

• The POS is an optional number that specifies where in the figure the

legend is placed.

Specifies the weight of the Light, Normal, Bold

FontWeight

characters. DEFAULT-Normal

Specify the color of the

Color Colr spcifiers

text.

Specify the color of the

Color specifiers

Background-Color edge of the rectangular

DEFAULT-None

box around the text.

LineWidth specifies the width of the Scalar(points)

edge of a rectangular box DEFAULT-0.5

Register Number: 10805057 Name: Mithun Mohandas

TYPES OF PLOTS:

• Vertical bar plot

ex: bar(x,y)

• Horizontal bar plot

ex: barh(x,y)

• Stairs plot

ex: stairs(x,y)

• Stem plot

ex : stem(x,y)

• Histograms

ex : hist(y)

SAMPLE PLOT:

Register Number: 10805057 Name: Mithun Mohandas

RESULT:

Thus the plot formation commands were executed successfully and the results were

obtained.

Ex. No.:

Date:

SAMPLING AND RANDOM VARIABLE

• When a value of the variable is the outcome of a statistical experiment that variable is

known as “Random variable” (RV).

Register Number: 10805057 Name: Mithun Mohandas

• Statistical experiment can have more than one possible outcome which is predictable.

The outcomes of a statistical experiment can be specified in advance as a sample

space as a set.

• Discrete random variable will take on a set of specific value each with

some probability.

distribution known as Discrete probability distribution.

Continuous probability distribution.

Infinitive to Positive Infinitive.

For example let A is a set of events. The event is described as, when flipping a coin

two times continuously the sample space will be S = {HH, TT, HT, TH}

Then if A is an event of number of heads in odd number.

Then Frequency of event A = 2

Total number of all possible trails=4

Then the Probability (A)= 2/4 = ½ = 0.5 and the formula for probability of an event is

given below:

Frequency of event A

probability(A) = ----------------------------------------

Total Number of all possible Trails

Register Number: 10805057 Name: Mithun Mohandas

frequently requires using a number (or set of numbers) that has a random

value. Matlab has two commands rand and randn that can be used to assign

random numbers to variables.

o The rand command generates uniformly distributed numbers with values

between 0 to 1. The command can be used to assign these numbers to a scalar,

a vector, or a matrix as shown in the following table.

RAND COMMAND:

Generates a single random number >>rand

rand

between 0 and 1. ans=0.2311

>>a=rand(1,4)

Generates an n elements row vector of a=

rand(1,n)

random number between 0 and 1. 0.6068 0.4860 0.8913

0.7621

>>b=rand(3)

Generates an m*n matrix with random 0.4565 0.4447 0.9218

rand(n)

between 0 and 1 0.0185 0.6154 0.7382

0.8214 0.7919 0.1763

>>c=rand(2, 4)

c=

Generates an m*n matrix with random 0.4057 0.9169 0.8936

rand(m, n)

between 0 and 1 0.3529

0.9355 0.4103 0.0579

0.8132

Generates a row vector with n elements >>randperm(8)

randperm(n) that are random permutation of integers ans=

1 through n 82743651

RESULT:

Thus the rand command was executed successfully and the results were obtained.

Ex. No.:

Register Number: 10805057 Name: Mithun Mohandas

WITHOUT USING BUILT IN FUNCTIONS

AIM:

Write a user defined matlab function file to find the mean and standard deviation of

given vector without using matlab built in functions.

ALGORITHM:

Step 1: Define a function definition line in which the input is a vector X and the

output as mean and standard deviation.

Step 2: Find the size of the vector

Step 3: Calculate the mean value using the formula mean= sum of all the

elements/total number of elements in a given vector. And print the mean value.

Step 4: Find the difference of all the elements with mean.

Step 5: Find the square value of the result of step 4.

Step 6: Find the mean of result of step 5

Step 7: Find the square root of the result of step 6

Step 8: Print the SD value

function[mean,SD]=meansd(x)

len=length(x);

b=0;

c=0;

for i=1:1:len

b=b+x(i);

end

meanx=b/len;

disp('the mean value of the given array is');

disp(meanx)

for j=1:1:len

y(j)=(x(j)-meanx)^2;

end

for k=1:1:len

c=c+y(k);

end

meany=c/len;

disp('the stdandard deviation of given array is');

disp((meany)^0.5)

Register Number: 10805057 Name: Mithun Mohandas

Execution Steps:

To run the function file meansd(x) first create a vector X and call the function in the

command window as follows.

>> X=[3, 7, 7, 19]

>> meansd(X)

Mean =

9

Standard Deviation =

6

RESULT:

Thus the user defined function meansd(X) was created successfully without using

the matlab built in functions and the results were obtained.

Register Number: 10805057 Name: Mithun Mohandas

Date: USING BUILT IN FUNCTIONS

AIM:

Write a user script to find the mean and standard deviation of given vector using

matlab built in functions.

MATLAB BUILT IN FUNCTIONS FOR MEAN AND SD:

• Mean(A)

• s = std(X)

• s = std(X,flag)

• s = std(X,flag,dim)

Definition:

There are two common textbook definitions for the standard deviation s of a data vector X.

where

The two forms of the equation differ only in versus in the divisor.

• Standard deviation SD=variance ½

• Variance can be defined as the averaging the squared distance of the values from the

mean value.

DESCRIPTION:

Mean(A):

Mean (A) will returns the mean value of the elements of the given vector A.

For example

>> A=[1 2 3 4 5]

>>mean(A)

A =

3

Register Number: 10805057 Name: Mithun Mohandas

s = std(X):

s = std(X), where X is a vector, returns the standard deviation using (1) above. The

result s is the square root of an unbiased estimator of the variance of the population from

which X is drawn, as long as X consists of independent, identically distributed samples. If X

is a matrix, std(X) returns a row vector containing the standard deviation of the elements of

each column of X. If X is a multidimensional array, std(X) is the standard deviation of the

elements along the first non singleton dimension of X.

s = std(X,flag):

s = std(X,flag) for flag = 0, is the same as std(X). For flag = 1, std(X,1) returns the

standard deviation using (2) above, producing the second moment of the set of values about

their mean.

s = std(X,flag,dim):

s = std(X,flag,dim) computes the standard deviations along the dimension of X

specified by scalar dim. Set flag to 0 to normalize Y by n-1; set flag to 1 to normalize by n.

RESULT:

Thus the commands were executed successfully by using the matlab built in

functions and the results were obtained.

Register Number: 10805057 Name: Mithun Mohandas

Ex. No.:

Date:

K-MEANS CLUSTERING ALGORITHM

AIM:

To write a matlab function for implementing K-Means clustering algorithm.

CLUSTERING:

• Clustering is the process by which discrete objects can be assigned to groups which

have similar characteristics.

• In clustering we are trying to group the data without assuming anything about the

population in advance.

• Clustering can be used to group like species, survey results, or satellite image data. By

learning to use a clustering algorithm, we can analyze the variety of data.

• A clustering algorithm will find the clusters of points based on the Euclidean distance

function. ie.. the distance between the two data points.

Step 1: Fix the random seed points in the given sample space and assign them as a

cluster centeroids.

Step 2: Find the pixels nearer to the seed point using distance functions and put them

in one cluster.

Step 3: Now reassign the cluster centeroid to the latest centeroid point.

Step 4: Repeat step 2 and 3 until the centeroid cease to change.

IDX = k_means(X, K) partititions the N x P data matrix X into K clusters through a fully

vectorized algorithm, where N is the number of data points and P is the number of

dimensions (variables). The partition minimizes the sum of point-to-cluster-centroid

Euclidean distances of all clusters. The returned N x 1 vector IDX contains the cluster indices

of each point. IDX = k_means(X, C) works with the initial centroids, C, (K x P).

[IDX, C] = k_means(X, K) also returns the K cluster centroid locations

in the K x P matrix, C.

Register Number: 10805057 Name: Mithun Mohandas

CODE:

function [gIdx,c]=kmeans(X,k)

N=200;

X = [randn(N,2)+ones(N,2); randn(N,2)-ones(N,2)];

[cidx, ctrs] = k_means(X, 2);

plot(X(cidx==1,1),X(cidx==1,2),'r.',X(cidx==2,1),X(cidx==2,2),'b.',

ctrs(:,1),ctrs(:,2),'kx');

[n,m]=size(X);

if ~isscalar(k)

c=k;

k=size(c,1);

else

c=X(ceil(rand(k,1)*n),:);

end

% allocating variables

g0=ones(n,1);

gIdx=zeros(n,1);

D=zeros(n,k);

% Main loop converge if previous partition is the same as current

while any(g0~=gIdx)

% disp(sum(g0~=gIdx))

g0=gIdx;

% Loop for each centroid

for t=1:k

d=zeros(n,1);

% Loop for each dimension

for s=1:m

d=d+(X(:,s)-c(t,s)).^2;

end

D(:,t)=d;

end

% Partition data to closest centroids

[z,gIdx]=min(D,[],2);

for t=1:k

c(t,:)=mean(X(gIdx==t,:));

end

% for t=1:m

Register Number: 10805057 Name: Mithun Mohandas

% c(:,t)=accumarray(gIdx,X(:,t),[],@mean);

% end

end

OUTPUT:

RESULT:

Register Number: 10805057 Name: Mithun Mohandas

and the results were obtained in a plot.

Ex. No.:

Date:

ROC CURVE CLASSIFICATION

AIM:

To implement ROC curve classification in matlab.

DESCRIPTION:

The Area Under an ROC Curve:

The graph given below shows three ROC curves representing excellent, good, and

worthless tests plotted on the same graph. The accuracy of the test depends on how well the

test separates the group being tested is a big question. Accuracy is measured by the area

under the ROC curve. The area measures discrimination, that is, the ability of the test to

correctly classify the given population into groups. An area of 1 represents a perfect test; an

area of .5 represents a worthless test. A rough guide for classifying the accuracy of a

diagnostic test is the traditional academic point system as given below:

• .80-.90 = good (B)

• .70-.80 = fair (C)

• .60-.70 = poor (D)

• .50-.60 = fail (F)

Register Number: 10805057 Name: Mithun Mohandas

The sensitivity and specificity of a diagnostic test depends on more than just the

"quality" of the test--they also depend on the definition of what constitutes an abnormal test.

Look at the the idealized graph given below showing the number of patients with and without

a disease arranged according to the value of a diagnostic test. This distributions overlap--the

test (like most) does not distinguish normal from disease with 100% accuracy. The area of

overlap indicates where the test cannot distinguish normal from disease. In practice, we

choose a cutpoint (indicated by the vertical black line) above which we consider the test to be

abnormal and below which we consider the test to be normal. The position of the cutpoint

will determine the number of true positive, true negatives, false positives and false negatives.

We may wish to use different cutpoints for different clinical situations if we wish to minimize

one of the erroneous types of test results.

Register Number: 10805057 Name: Mithun Mohandas

• False positive: Healthy people wrongly identified as sick

• True negative: Healthy people correctly identified as healthy

• False negative: Sick people wrongly identified as healthy

CODE:

function area = roc(fileName,varargin)

%

% RECEIVER-OPERATING CHARACTERISTICS (ROC) CURVE

%

% Receiver-Operating Characteristics (ROC) curve and the area

% under the curve is returned for one or more experiments on the

% same dataset.

%

% area = roc(fileName,exp)

%

% fileName: The name of the output file. It is an image

% exp: a structure representing an experiment with three fields

% - exp.name: a string specifying the experiment name

% - exp.positive_n: the number of positive samples in the experiment

% - exp.likelihoods: likelihoods of each sample where the first

% exp.positive_n number of likelihoods belongs to the positive

Register Number: 10805057 Name: Mithun Mohandas

% area: a 1x1-dimensional cell array of the area under the roc curve.

%

% The function works for unlimited number of experiments. Therefore, the

followings

% are all possible.

%

% area = roc(fileName,exp1,exp2)

% fileName: the same as above.

% exp1: the same as exp given above.

% exp2: another experiment result on the same dataset.

% area: a 1x2-dimensional cell array of the area under the roc curves.

%

% Similarly,

% area = roc(fileName,exp1,exp2,...,expN) is also possible.

%

% Example:

% x.name = 'experiment-1';

% x.positive_n = 500;

% x.likelihoods = rand(1,1000);

% y.name = 'experiment-2';

% y.positive_n = 500;

% y.likelihoods = rand(1,1000);

% area = roc('sample_compare.jpg',x,y);

colors='bgrcmyke';

types='.ox+*sw';

exp_n = nargin-1; % number of experiments

handle=figure; hold on; title('RECIEVER-OPERATING CHARACTERISTICS (ROC)

CURVE');

xlabel('FALSE POSITIVE RATIO'); ylabel('TRUE POSITIVE RATIO'); axis([-0.01

1.00001 -0.0001 1.00001]);

leg_names = cell(1,exp_n); %leg_names{nargin} = '';

area = cell(1,exp_n);

for i=1:1:exp_n % for all experiments

scolor=colors(mod(i,size(colors,2))); stype=types(mod(i,size(types,2)));

leg_names{i} = varargin{i}.name;

likelihoods = varargin{i}.likelihoods;

temp = sort(likelihoods, find(size(likelihoods) == max(size(likelihoods)),1),

'descend');

nb_total = max(size(temp));

nb_pos = varargin{i}.positive_n;

nb_neg = nb_total - nb_pos;

prob_true_pos = zeros(1,nb_pos + nb_neg+1);

for j=1:1:max(size(temp)) % for all thresholds

thr=temp(j);

prob_true_pos(j+1) = sum(likelihoods(1:nb_pos) >= thr) / nb_pos;

prob_false_pos(j+1) = sum(likelihoods((nb_pos+1):end) >= thr) / nb_neg;

end

Register Number: 10805057 Name: Mithun Mohandas

plot(prob_false_pos, prob_true_pos, form);

area{1,i} = sum((prob_false_pos(2:end)-prob_false_pos(1:end-1)).*...

(prob_true_pos(2:end)+prob_true_pos(1:end-1))/2);

end

legend(leg_names,'Location','SouthEast');

fprintf('SAVING FILE %s\n',fileName);

saveas(handle,fileName);

hold off;

Execution steps:

x.name = 'experiment-1';

x.positive_n = 500;

x.likelihoods = rand(1,1000);

y.name = 'experiment-2';

y.positive_n = 500;

y.likelihoods = rand(1,1000);

area = roc('image.jpg',x,y);

>> x

x=

name: 'experiment-1'

>> x.likelihoods = rand(1,1000)

x.name=’experiment-1'

x.positive=500

likelihoods: [1x1000 double]

>> roc('image.jpg',x)

SAVING FILE image.jpg

ans = [0.5097]

OUTPUT:

Register Number: 10805057 Name: Mithun Mohandas

RESULT:

successfully and the results were obtained in a plot.

## Molto più che documenti.

Scopri tutto ciò che Scribd ha da offrire, inclusi libri e audiolibri dei maggiori editori.

Annulla in qualsiasi momento.