matlab 2008 record
TRANSCRIPT
-
8/7/2019 Matlab 2008 Record
1/50
Register Number: 10805057 Name: Mithun Mohandas
Ex. No.: MATLAB BASICSDate:
AIM:To study the basics about the matlab environment.
INTRODUCTION:
MATLAB is a powerful language for technical computing.
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
and processing, visualization and graphics and algorithm development.
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.
Launch Window Provides access to tools, demos, anddocumentation.
Command History Window Logs commands entered in the commandwindow.
Workspace Window Provide information about the variables thatare used.Current Directory Window Show that files in the current directory.
BASIC MATLAB COMMANDS:
Command OutcomeClear Removes all variable from the memory.
Clear x y z Removes only variables x, y and z from thememory.
Who Displays a list of variables currently in thememory.
Whos Displays a list of the variable currently in thememory and their size together with
BP 217 Computer Practice Laboratory Page No.:
-
8/7/2019 Matlab 2008 Record
2/50
Register Number: 10805057 Name: Mithun Mohandas
information about their bytes and class.
Notes about Variables (scalar, vector, matrix) in MATLAB
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:
a b
>> whos
Name Size Bytes Class
a 1x1 8 double array
b 1x1 8 double array
Grand total is 2 element using 16 bytes
Strings as matlab variables
BP 217 Computer Practice Laboratory Page No.:
-
8/7/2019 Matlab 2008 Record
3/50
Register Number: 10805057 Name: Mithun Mohandas
>> B=Matlab is easy
B =
Matlab is easy
MATLAB WORKING ENVIRONMENT:
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.
BP 217 Computer Practice Laboratory Page No.:
-
8/7/2019 Matlab 2008 Record
4/50
Register Number: 10805057 Name: Mithun Mohandas
RESULT:
Thus all the matlab basic commands were executed successfully and the resultswere obtained.Ex. No.: OPERATORS AND BUILT-IN FUNCTIONS IN
MATLABDate:
AIM:
To study all the operators available in matlab (like arithmetic, relational, logical) and
built-in math functions.
OPERATORS IN MATLAB:
I) ARITHMETIC OPERATORS
II) BUILTIN MATH FUNCTIONS
III) RELATIONAL AND LOGICAL OPERATORS
IV) ROUNDING FUNCTIONS
I) ARITHMETIC OPERATORS:
Operators Symbol Example
Addition + 5+5Subtraction - 5-3Multiplication * 5*3Right Division / 5/3Left Division \ 5\3=3\5Exponentiation ^ 5^3
Example:>>a=5
a =5
>>b=3
BP 217 Computer Practice Laboratory Page No.:
-
8/7/2019 Matlab 2008 Record
5/50
Register Number: 10805057 Name: Mithun Mohandas
b=3
>>c=a+b
C=8
>>c=a-bc=2
>>c=a*b
c=15
>>c=a/b
c=1.6667
>>c=a\b
c=0.6000>>c=a^b
c=125
II) BUILTIN MATH FUNCTIONS:
Function Descriptionsqrt(x) Square rootexp(x) Exponential
abs(x) Absolute valuelog(x) Natural logrithmBase e logrithm(ln)log10(x) Base 10 logrithm
factorial(x) The factorial function 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)
BP 217 Computer Practice Laboratory Page No.:
-
8/7/2019 Matlab 2008 Record
6/50
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
III) RELATIONAL AND LOGICAL OPERATORS:
Relational Operator Description< Less than> Greater than
= Greater than or equal to== Equal to
Example:
>>5>8
ans=0
>>a=5>y=(68)+(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
BP 217 Computer Practice Laboratory Page No.:
-
8/7/2019 Matlab 2008 Record
7/50
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=A0, -1ifx>round(17/5)
ans=3>>fix(13/5)
ans=2
>>ceil(11/5)
ans=3
>>floor(-9/4)
ans=-3
>>rem=13,5)
BP 217 Computer Practice Laboratory Page No.:
-
8/7/2019 Matlab 2008 Record
8/50
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.: SCRIPT FILES IN MATLAB- AN INTRODUCTIONDate:
A script file is a series of MATLAB commands, also called a program.
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.
BP 217 Computer Practice Laboratory Page No.:
-
8/7/2019 Matlab 2008 Record
9/50
Register Number: 10805057 Name: Mithun Mohandas
RESULT:
Thus the matlab script file was created successfully.Ex. No.: IF-ELSE LOOP- WORKERS PAYDate:
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)
% the script file calculating the pay of worker
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);
BP 217 Computer Practice Laboratory Page No.:
-
8/7/2019 Matlab 2008 Record
10/50
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 hours worked 398enter the value of hourly wage 45
pay =17910
RESULT:
Thus the matlab script to calculate the employees salary wage was executed
successfully.
Ex. No.: IF-ELSE LOOP- FAHRENHEIT TO CELCIUSDate:
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:
while 1 % use of an infinite loop
TinF = input(Temperature in F: ); % get input
if isempty(TinF) % how to get out
break
BP 217 Computer Practice Laboratory Page No.:
-
8/7/2019 Matlab 2008 Record
11/50
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.: FOR END LOOP- SUM OF FIRST N NUMBERSDate:
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 valueCODE:
%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
BP 217 Computer Practice Laboratory Page No.:
-
8/7/2019 Matlab 2008 Record
12/50
Register Number: 10805057 Name: Mithun Mohandas
fprintf('the sum of n number is %f',sum);
OUTPUT:
enter the value of n2
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.:FOR END LOOP- SUM OF DIGITSDate:
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
a. Add up the values of the elements (Check with sum.)
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)
BP 217 Computer Practice Laboratory Page No.:
-
8/7/2019 Matlab 2008 Record
13/50
Register Number: 10805057 Name: Mithun Mohandas
total = total + x(j);
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.: FOR END LOOP- ARRAY MANIPULATIONDate:
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;
BP 217 Computer Practice Laboratory Page No.:
-
8/7/2019 Matlab 2008 Record
14/50
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.:SIMPLE INTEREST AND COMPOUND INTERESTDate:
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)
% the script file calculate the compound interest
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;
BP 217 Computer Practice Laboratory Page No.:
-
8/7/2019 Matlab 2008 Record
15/50
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 principle1000enter the value of rate10enter the value of year5the ci isci = 1.6105e+003the si issi = 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 ARRAYSINGLE DIMENSIONDate:
AIM: To study all the built in functions for the manipulation with the single dimensional
arrays.
BUILT-IN ARRAY FUNCTIONS:
Function Description Example
mean(A)
If A is a vector,return the meanvalue of theelement of thevector.
>>A=[5 9 2 4];>>mean(A)ans=5
BP 217 Computer Practice Laboratory Page No.:
-
8/7/2019 Matlab 2008 Record
16/50
Register Number: 10805057 Name: Mithun Mohandas
c=max(A)
If A is the vector,C is the largestelement in A. If A
is a matrix , C is arow vector containing thelargest element of each column of A.
>>A=[5 9 2 4 11 6 7 11 0 1];>>C=max(A)
C=11>>[d,n]=max(A)d=11n=5
>>[d,n]=max(A)d=11n=5
[d,n]=max(A)if A is a vector, d is the largest elementin A. N is the position of the element(the first if several have the maxvalue).
min(A)The same as themax(A), but for the smallestelement.
>>A=[5 9 2 4];
[d,n]=min(A)
The same as[d,n]=max(A), butfor the smallestelement.
>>min(A)ans=2
sum(A)
if A the vector ,arranges theelements of thevector.
>>A=[5 9 2 4];>>sum(A)
ans=20
sort(A)
If A is the vector,arranges theelements of thevector inascending order.
>>A=[5 9 2 4];>>sort(A)ans=2 4 5 9
Function Description Example
median(A)
If A the vector, returns the
median value of theelements of the vectors.
>>A=[5 9 2 4];
>>median(A)ans=4.5000
std(A)If A is a vector, return thestandard deviation of theelements of the vectors
>>A=[5 9 2 4];>>std(A)ans=2.9439
det(A) Returns the determinant of a square matrix A
>>A=[5 9 2 4];det(A)ans=-2
dot(a,b)
Calculates the scaler (dot)product of two vectors aand b. The vectors can
each be row or columnvectors.
>>a=[1 2 3];>>b=[2 4 1];>>dot(a,b)ans=26
BP 217 Computer Practice Laboratory Page No.:
-
8/7/2019 Matlab 2008 Record
17/50
Register Number: 10805057 Name: Mithun Mohandas
cross(a,b)
Calculate the cross productof two product of twovectors a and b, (axib). Thetwo vectors must have 3elements.
>>a=[1 2 3];>>b=[2 4 1];>>cross(a,b)ans= -5 3 -2
inv(A) Returns the inverse of asquare matrix A.
>>A=[2 -2 1;3 2 -1;2 -3 2];>>inv(A)ans=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 ARRAYSINGLE DIMENSIONDate:
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
BP 217 Computer Practice Laboratory Page No.:
-
8/7/2019 Matlab 2008 Record
18/50
Register Number: 10805057 Name: Mithun Mohandas
>>X=[1 2 3 4 5]
>>X(3)
Ans =
3Adding 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
BP 217 Computer Practice Laboratory Page No.:
-
8/7/2019 Matlab 2008 Record
19/50
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
Creating a two dimensional array (matrix) using colon : operator
>> X=[[1:1:3];[1:1:3];[1:1:3]]
X =
1 2 31 2 3
1 2 3
Creating a two dimensional array (matrix) using line space
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 DIMENSIONALARRAY- MATRIX OPERATIONSDate:
AIM: To create a two dimensional array and perform all the matrix operations like matrix
addition, subtraction and multiplication.
DESCRIPTION:
BP 217 Computer Practice Laboratory Page No.:
-
8/7/2019 Matlab 2008 Record
20/50
Register Number: 10805057 Name: Mithun Mohandas
A two dimensional array is known as a matrix. A matrix has numbers in rows
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 00 0 0 00 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 11 1 11 1 11 1 1
Creating a two dimensional array with all the diagonal elements are equal to 1
>>A=eye(3)A =
1 0 00 1 00 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:
>>A= [1 2 3;4 5 6;7 8 9];
>>B=[1 2 3
4 5 6
7 8 9] ;
BP 217 Computer Practice Laboratory Page No.:
-
8/7/2019 Matlab 2008 Record
21/50
Register Number: 10805057 Name: Mithun Mohandas
>>C=A+B
C =
2 4 68 10 1214 6 18
MATRIX SUBSTRACTION:
>>C=A-B
0 0 00 0 00 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 4266 81 96102 126 150
MATRIX TRANSPOSE>>A=[1 2;3 4]
>>B=A
B= 1 32 4
Finding the size of the array
>>A =[1 2 3;4 5 6;7 8 9]
>>A =
1 2 3
4 5 6
7 8 9
>>size(A)
BP 217 Computer Practice Laboratory Page No.:
-
8/7/2019 Matlab 2008 Record
22/50
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 00 8 0
USING COLON : IN ADDRESSING ARRAYS
A colon can be used to address a range of elements in a vector or a matrix.
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.
BP 217 Computer Practice Laboratory Page No.:
-
8/7/2019 Matlab 2008 Record
23/50
Register Number: 10805057 Name: Mithun Mohandas
USING COLON : IN ADDRESSING ARRAYS
>>A =[1 2 3;4 5 6;7 8 9]
>>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.: SOLVING MATHEMATICAL EXPRESSIONS - IDate:
AIM: Create a vector x with the elements,
xn = (-1)n+1/(2n-1)
Add up the elements of the version of this vector that has 100 elements.
CODE :
BP 217 Computer Practice Laboratory Page No.:
-
8/7/2019 Matlab 2008 Record
24/50
Register Number: 10805057 Name: Mithun Mohandas
n = 1:100;
X = ( (-1).^(n+1) ) ./ (2*n - 1);
Y=sum(X)
OUTPUT:
Y =
0.7829
RESULT:
Thus the given mathematical expression was executed successfully and the results
were obtained.Ex. No.: SOLVING MATHEMATICAL EXPRESSIONS - IIDate:
AIM: Write down the MATLAB expressions that will correctly compute the following:
a. ln(2 + t + t 2)
b. e t(1 + cos(3t))
c. cos2
(t) + sin2
(t)
BP 217 Computer Practice Laboratory Page No.:
-
8/7/2019 Matlab 2008 Record
25/50
Register Number: 10805057 Name: Mithun Mohandas
d. tan -1(1) (this is the inverse tangent function)
e. cot(t)
f. sec 2(t) + cot(t) - 1
Test that your solution works for t = 1:0.2:2CODE:
>>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.: SOLVING MATHEMATICAL EXPRESSIONS - IIIDate:
BP 217 Computer Practice Laboratory Page No.:
-
8/7/2019 Matlab 2008 Record
26/50
Register Number: 10805057 Name: Mithun Mohandas
AIM: Write down the MATLAB expressions that will correctly compute the following:
Use the following commands to create an array called F:
>> 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
BP 217 Computer Practice Laboratory Page No.:
-
8/7/2019 Matlab 2008 Record
27/50
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 100.5729 0.9134
None were different at 90% LOC (all < 2.132).
BP 217 Computer Practice Laboratory Page No.:
-
8/7/2019 Matlab 2008 Record
28/50
Register Number: 10805057 Name: Mithun Mohandas
RESULT:Thus the given mathematical expression was executed successfully and the results
were obtained.
Ex. No.: SOLVING MATHEMATICAL EXPRESSIONS - IVDate:
AIM: Write down the MATLAB expressions that will correctly compute the following:
Given the array A = [ 2 4 1 ; 6 7 2 ; 3 5 9], provide the commands needed to
a. assign the first row of A to a vector called x1
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
BP 217 Computer Practice Laboratory Page No.:
-
8/7/2019 Matlab 2008 Record
29/50
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
BP 217 Computer Practice Laboratory Page No.:
-
8/7/2019 Matlab 2008 Record
30/50
Register Number: 10805057 Name: Mithun Mohandas
RESULT:
Thus the given mathematical expression was executed successfully and the results
were obtained.Ex. No.: SOLVING MATHEMATICAL EXPRESSIONS - VDate:
AIM:
Write down the MATLAB expressions that will correctly compute the following:
If A = [2 7 9 7 ; 3 1 5 6 ; 8 1 2 5] then do the following
a. assign the even-numbered columns of A to an array called B
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 =
BP 217 Computer Practice Laboratory Page No.:
-
8/7/2019 Matlab 2008 Record
31/50
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 67 5 5
BP 217 Computer Practice Laboratory Page No.:
-
8/7/2019 Matlab 2008 Record
32/50
Register Number: 10805057 Name: Mithun Mohandas
RESULT:
Thus the given mathematical expression was executed successfully and the results
were obtained.
Ex. No.:PLOT FORMATIONDate:
A plot commond used to create a plot.
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.
The first method is useful is when a PLOT command is a part of a
computer program(script file).
FORMATTING OF PLOT USING COMMANDS
The formatting commands are entered after the PLOT or the FPOT commands
The various formatting commands are-
a. The X-LABEL and Y-LABEL 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)
b-The TITLE commands:-
title(text as string)
BP 217 Computer Practice Laboratory Page No.:
-
8/7/2019 Matlab 2008 Record
33/50
-
8/7/2019 Matlab 2008 Record
34/50
Register Number: 10805057 Name: Mithun Mohandas
arround the text.
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:
BP 217 Computer Practice Laboratory Page No.:
-
8/7/2019 Matlab 2008 Record
35/50
Register Number: 10805057 Name: Mithun Mohandas
RESULT:
Thus the plot formation commands were executed successfully and the results were
obtained.
Ex. No.: SAMPLING AND RANDOM VARIABLEDate:
When a value of the variable is the outcome of a statistical experiment that variable is
known as Random variable (RV).
A RV is determined by a chance of event.
BP 217 Computer Practice Laboratory Page No.:
-
8/7/2019 Matlab 2008 Record
36/50
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.
There are two kinds of Random variable.
1. Discrete Random variable
Discrete random variable will take on a set of specific value each with
some probability.
Discrete RV has known probability of occurance and its probability
distribution known as Discrete probability distribution.
2. Continuous Random variable
Continuous RV has its probability between 0 to 1 and it has associated
Continuous probability distribution.
The random variable would take value in the range of Negative
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:
Generation of Random Numbers using matlab:
BP 217 Computer Practice Laboratory Page No.:
Frequency of event A
probability(A) = ----------------------------------------
Total Number of all possible Trails
-
8/7/2019 Matlab 2008 Record
37/50
Register Number: 10805057 Name: Mithun Mohandas
o Simulation of many physical processes and engineering applications
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:
COMMAND DESCRIPTION EXAMPLE
randGenerates a single random number between 0 and 1.
>>randans=0.2311
rand(1,n) Generates an n elements row vector of random number between 0 and 1.
>>a=rand(1,4)a=0.6068 0.4860 0.89130.7621
rand(n) Generates an m*n matrix with randombetween 0 and 1
>>b=rand(3)0.4565 0.4447 0.92180.0185 0.6154 0.73820.8214 0.7919 0.1763
rand(m, n) Generates an m*n matrix with randombetween 0 and 1
>>c=rand(2, 4)
c=0.4057 0.9169 0.89360.35290.9355 0.4103 0.05790.8132
randperm(n)Generates a row vector with n elementsthat are random permutation of integers1 through n
>>randperm(8)ans=8 2 7 4 3 6 5 1
RESULT:
Thus the rand command was executed successfully and the results were obtained.
Ex. No.:
BP 217 Computer Practice Laboratory Page No.:
-
8/7/2019 Matlab 2008 Record
38/50
Register Number: 10805057 Name: Mithun Mohandas
FINDING MEAN AND STANDARD DEVIATION -WITHOUT USING BUILT IN FUNCTIONS
Date:
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
CODE: (meansd.m is a user defined function file)
function[mean,SD]=meansd(x)len=length(x);b=0;c=0;for i=1:1:len
b=b+x(i);endmeanx=b/len;disp('the mean value of the given array is');
disp(meanx)
for j=1:1:leny(j)=(x(j)-meanx)^2;
end for k=1:1:len
c=c+y(k);endmeany=c/len;disp('the stdandard deviation of given array is');disp((meany)^0.5)
BP 217 Computer Practice Laboratory Page No.:
-
8/7/2019 Matlab 2008 Record
39/50
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 thecommand 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.
BP 217 Computer Practice Laboratory Page No.:
-
8/7/2019 Matlab 2008 Record
40/50
Register Number: 10805057 Name: Mithun Mohandas
Ex. No.: FINDING MEAN AND STANDARD DEVIATION -USING BUILT IN FUNCTIONSDate:
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
and is the number of elements in the sample.
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
BP 217 Computer Practice Laboratory Page No.:
-
8/7/2019 Matlab 2008 Record
41/50
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 Xis 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.
BP 217 Computer Practice Laboratory Page No.:
-
8/7/2019 Matlab 2008 Record
42/50
Register Number: 10805057 Name: Mithun Mohandas
Ex. No.: K-MEANS CLUSTERING ALGORITHMDate:
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 whichhave similar characteristics.
In clustering we are trying to group the data without assuming anything about thepopulation in advance.
Clustering can be used to group like species, survey results, or satellite image data. Bylearning 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 distancefunction. ie.. the distance between the two data points.
K-MEANS CLUSTERING ALGORITHM:
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.
DESCRIPTION OF THE MATLAB CODE FOR K-MEANS ALGORITHM:
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.
BP 217 Computer Practice Laboratory Page No.:
-
8/7/2019 Matlab 2008 Record
43/50
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);
% Check if second input is centroidsif ~isscalar(k)c=k;k=size(c,1);
elsec=X(ceil(rand(k,1)*n),:);
end
% allocating variablesg0=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 dimensionfor s=1:m
d=d+(X(:,s)-c(t,s)).^2;endD(:,t)=d;
end% Partition data to closest centroids
[z,gIdx]=min(D,[],2);
% Update centroids using means of partitionsfor t=1:k
c(t,:)=mean(X(gIdx==t,:));end
% for t=1:m
BP 217 Computer Practice Laboratory Page No.:
-
8/7/2019 Matlab 2008 Record
44/50
Register Number: 10805057 Name: Mithun Mohandas
% c(:,t)=accumarray(gIdx,X(:,t),[],@mean);% endend
OUTPUT:
RESULT:
BP 217 Computer Practice Laboratory Page No.:
-
8/7/2019 Matlab 2008 Record
45/50
Register Number: 10805057 Name: Mithun Mohandas
Thus the K-Means clustering algorithm was implemented in matlab successfully
and the results were obtained in a plot.
Ex. No.: ROC CURVE CLASSIFICATIONDate:
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:
The given population is classified according to the following ranges
.90-1 = excellent (A) .80-.90 = good (B) .70-.80 = fair (C) .60-.70 = poor (D) .50-.60 = fail (F)
BP 217 Computer Practice Laboratory Page No.:
-
8/7/2019 Matlab 2008 Record
46/50
Register Number: 10805057 Name: Mithun Mohandas
The sensitivity and specificity:
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.
BP 217 Computer Practice Laboratory Page No.:
-
8/7/2019 Matlab 2008 Record
47/50
Register Number: 10805057 Name: Mithun Mohandas
True positive: Sick people correctly diagnosed as sick 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
BP 217 Computer Practice Laboratory Page No.:
-
8/7/2019 Matlab 2008 Record
48/50
Register Number: 10805057 Name: Mithun Mohandas
% samples while others belong to the negative samples.% area: a 1x1-dimensional cell array of the area under the roc curve.%% The function works for unlimited number of experiments. Therefore, thefollowings% 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 experimentshandle=figure; hold on; title('RECIEVER-OPERATING CHARACTERISTICS (ROC)CURVE');xlabel('FALSE POSITIVE RATIO'); ylabel('TRUE POSITIVE RATIO'); axis([-0.011.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
BP 217 Computer Practice Laboratory Page No.:
-
8/7/2019 Matlab 2008 Record
49/50
Register Number: 10805057 Name: Mithun Mohandas
form = sprintf('-%c%c', scolor, stype);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);
endlegend(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);
>> xx =name: 'experiment-1'
>> x.positive_n = 500;>> x.likelihoods = rand(1,1000)
x.name=experiment-1'x.positive=500
likelihoods: [1x1000 double]
>> roc('image.jpg',x)SAVING FILE image.jpgans = [0.5097]
OUTPUT:
BP 217 Computer Practice Laboratory Page No.:
-
8/7/2019 Matlab 2008 Record
50/50
Register Number: 10805057 Name: Mithun Mohandas
RESULT:
Thus the ROC Curve classification algorithm was implemented in matlab
successfully and the results were obtained in a plot.