Upload
duongtram
View
222
Download
3
Embed Size (px)
Citation preview
INDEX
S.No. Practical Name Date Remark
1 Introduction to MATLAB Environment.
2 Introduction to MATLAB as a Calculator.
3 Introduction to MATLAB as a MATRIX manipulation.
4 Introduction To Script file and Function File.
5 Write a Script File to Plot a sin curve.
6 Write a Script file to calculate the factorial of a
number.
7 Write a Function file to print Fibonnaci series.
8 Write a Script File for Keyboard command.
9 Write a Script file to plot a circle of given radius.
10 Explain the command who. whos , clear, save, load,
clear all, & diary command.
11. Write a script file to create a menu with mane circle plot and two Option Cartesian and polar.
12 Write a Script File to Generate and write a
temperature table.
13 Create an Structure array that store multiple record.
14 Write a Cell Script to publish a report using MATLAB
15 Plot the Expression (for grouth of the population). Given:- Where t is the date in Years and t=[1790 to 2000].
16.
Write a Script file to compute sine series of the
given Value of ‘x’ and ‘n’ using given Formula.
17.
Write a Function File to compute sine series of
given Value of ‘x’ and ‘n’ using given Formula.
18.
Write a Function file to find whether a given
number is even, if even it returns even
otherwise returns 0.
19.
Make a plot of the function f(x) =sin(1/x) for 0.01<x<0.1 . How did you create x so that the plot looked good.
Aim :-Brief Introduction to MATLAB .
INTRODUCTION:
MATLAB stands for Matrix Laboratory. MATLAB was written originally to provide easy access to
matrix software developed by the LINPACK (linear system package) and EISPACK (Eigen system
package) projects.
MATLAB is a high-performance language for technical computing. It integrates Computation,
visualization, and programming environment. Furthermore, MATLAB is a Modern programming
language environment: it has sophisticated data structures, contains
Built-in editing and debugging tools, and supports object-oriented programming. These factors
Make MATLAB an excellent tool for teaching and research. MATLAB has many advantages
compared to conventional computer languages (e.g., C, FORTRAN) for solving technical
problems. MATLAB is an interactive system whose basic data element is an array that does not
require dimensioning. The software package has been commercially available since 1984 and is
now considered as a standard tool at most universities and industries worldwide.
It has powerful built-in routines that enable a very wide variety of computations. It also has
easy to use graphics commands that make the visualization of results immediately available.
Specific applications are collected in packages referred to as toolbox. There are toolboxes for
signal processing, symbolic computation, control theory, simulation, optimization, and several
other fields of applied science and engineering.
MATLAB Desktop
When you start MATLAB, the MATLAB desktop appears, containing tools (graphical user
interfaces) for managing files, variables, and applications associated with MATLAB.
The first time MATLAB starts, the desktop appears as shown in the following illustration.
Command Description Example
Cd Display current directory
Change current directory
cd
cd
c:\experiments\hoo
Dir Display file names in current
directory
dir
Edit Launch MATLAB editor edit hoo.m
Delete Delete files delete hoo.m
Help Display help for MATLAB functions in
Command Window
help screen
Helpdesk Display Help browser Helpdesk
For running experiments, it might be safer to use MATLAB with -nojvm option, because the window system (above) does not always accept the getchar function.
Variables
Global Variables: If you want more than one function to share a single copy of a variable,
simply declare the variable as global in all the functions. Do the same thing at the command line
if you want the base workspace to access the variable. The global declaration must occur before
the variable is actually used in a function. Although it is not required, using capital letters for the
names of global variables helps distinguish them from other variables. For example, create an M-
file called falling.m.
function h = falling(t)
global GRAVITY
h = 1/2*GRAVITY*t.^2;
Persistent Variables: If you want the same function to keep using the same variable, on subsequent runs of the function, use a persistent variable.
Characteristics of persistent variables are
You can declare and use them within M-file functions only. Only the function in which the variables are declared is allowed access to it. MATLAB does not clear them from memory when the function exits, so their value is
retained from one function call to the next.
You must declare persistent variables before you can use them in a function. It is usually best to
put your persistent declarations toward the beginning of the function. You would declare
persistent variable SUM_X as follows:
persistent SUM_X
If you clear a function that defines a persistent variable (i.e., using clear functionname or
clear all), or if you edit the M-file for that function, MATLAB clears all persistent variables
used in that function.
You can use the mlock function to keep an M-file from being cleared from memory, thus
keeping persistent variables in the M-file from being cleared as well.
Initializing Persistent Variables. When you declare a persistent variable, MATLAB initializes
its value to an empty matrix, []. After the declaration statement, you can assign your own value
to it. This is often done using an isempty statement, as shown here:
function findSum(inputvalue)
persistent SUM_X
if isempty(SUM_X)
SUM_X = 0;
end
SUM_X = SUM_X + inputvalue
This initializes the variable to 0 the first time you execute the function, and then accumulates the
value on each iteration.
Arithmetic Operators
Operator Description
+ Addition
- Subtraction
* Multiplication
/ Right division
\ Left division
^ Power
: Colon operator
Relational Operators
Operator Description
< Less than
<= Less than or equal
to
> Greater than
>= Greater than or
equal to
== Equal to
~= Not equal to
Logical Operators
A = [0 1 1 0 1];
B = [1 1 0 0 1];
E = [1 2 5 3];
Operator Description Example
&
Returns 1 for every element location that is
true (nonzero) in both arrays, and 0 for all
other elements.
A & B = 01001
| Returns 1 for every element location that is
true (nonzero) in either one or the other, or
both, arrays and 0 for all other elements.
A | B = 11101
~ Complements each element of input array, A. ~A = 10010
xor
Returns 1 for every element location that is
true (nonzero) in only one array, and 0 for all
other elements.
xor(A,B)=10100
Matlab Common Symbols and Operations
Symbol Description Example
*
An asterisk in a filename specification is
used as a wildcard specifier.
Dir(‘January_*.mat)
Will find all m files
containing
January_*.
: The colon operator generates a sequence
of numbers that you can use in creating or
indexing into arrays.
--C = A(1, 2: 4)
Creates C = [1 0 0]
-- N = 1:40
Creates a sequence
of incremental
numbers from 1 to
40. You can also use
the syntax
-N= first:step:last
For other
increments
, A comma is used to separate the following
types of elements.
-Separate elements
belonging in the
same row C=[1,0,0]
-Separate indexes of
an array D=E(1,2)
D=[2]
-Separate
arguments when
calling a function.
.
Add fields to a MATLAB structure by
following the structure name with a dot
and then a field name:
-DATA(i).rt =
reactiontime
-DATA(i).trial = i
… To continue a Matlab statement on a
different line
() Parentheses are used mostly for indexing
into elements of an array or for specifying
arguments passed to a called function.
A(1)
; The semicolon can be used to construct
arrays, suppress output from a MATLAB
command, or to separate commands
entered on the same line.
E = [1 2;5 3]
‘ ‘ Single quotes are the constructor symbol
for MATLAB character arrays.
S = 'Hello
World'
[] Square brackets are used to delimitate the
contents of a matrix. But empty square
brackets are used to DELETE rows or
columns of a matrix.
E(:,2)=[]
E = [1
5]
Operator Precedence
You can build expressions that use any combination of arithmetic, relational, and logical operators. Precedence levels determine the order in which MATLAB evaluates an expression. Within each precedence level, operators have equal precedence and are evaluated from left to right. The precedence rules for MATLAB operators are shown in this list, ordered from highest precedence level to lowest precedence level:
1. Parentheses () 2. Transpose (.'), power (.^), complex conjugate transpose ('), matrix power (^) 3. Unary plus (+), unary minus (-), logical negation (~) 4. Multiplication (.*), right division (./), left division(.\), matrix multiplication (*), matrix
right division (/), matrix left division (\) 5. Addition (+), subtraction (-) 6. Colon operator (:) 7. Less than (<), less than or equal to (<=), greater than (>), greater than or equal to (>=),
equal to (==), not equal to (~=) 8. Element-wise AND (&) 9. Element-wise OR (|) 10. Short-circuit AND (&&) 11. Short-circuit OR (||)
Some mathematical functions
Y = round(X) Round to nearest integer
Y = fix(X) Round towards zero
Y = ceil(X) Round toward infinity
Y = floor(X) Round towards minus infinity
Y = mod(N,n) Modulus after division
Y = rem(N,n) Remainder after division
Y = abs(X) Absolute value and complex magnitude
Y = sqrt(X) Square root
Keywords
MATLAB reserves certain words for its own use as keywords of the language. To list the keywords, type
iskeyword
ans =
'break' 'function
'
'case' 'global'
'catch' 'if'
'continue' 'otherwis
e'
'else' 'persiste
nt'
'elseif' 'return'
'end' 'switch'
'for'
'try'
Aim :- Write A script File For example of keyboard command.
a = ones(10);
for i=1:10
disp(i)
a(:,i)=i*a(:,i);
if i==5
keyboard
end
end
Output :-
>>a =
1
2
3
4
5
K>> return
6
7
8
9
10
Aim:- Write a script file to create a menu with name circle plot
and two option Cartesian & polar.
Sol :-
% plotting a circle.
r=input('Enter the desires radies');
theta = linspace(0,2*pi,100);
r = r*ones(size(theta));
coord=menu('circle plot','cartesian','polar');
if coord==1 % if first option is selected
plot(r.*cos(theta),r.*sin(theta))
axis('square')
else
polar(theta,r);
end
output:
enter value of radius 8
If you click on Cartesian on dialog box. Then following figure
comes appers.
If you click on polar on dialog box. Then following figure comes
appers
-8 -6 -4 -2 0 2 4 6 8-8
-6
-4
-2
0
2
4
6
8
2
4
6
8
30
210
60
240
90
270
120
300
150
330
180 0
Aim :- Create an structure array that store mltiple record.
>> fallsem(2).course='sna';
>> fallsem(2).prof='mohan';
>> fallsem(2).score=[32 43 54];
>> fallsem
fallsem =
1x2 struct array with fields:
course
prof
score
>> fallsem(2).course
ans =
sna
>> fallsem(3).course='cds';
>> fallsem(3).prof='narendra';
>> fallsem(3).score=[23 65 77];
>> fallsem
fallsem =
1x3 struct array with fields:
course
prof
Aim - Write a Script File named sine series to evaluate sine series for given
value of x & n using given formula.
Sol :-
sinseries(x)
n=input('enter the number of terms in sin')
for k=1:n
sum=sum+(-1)^(k-1)*(x^(2*k -1))/(fact(2*k-1));
end
Output :_
> sinseries
enter the value of xpi/6
Enter the no. of terms in sine series
sum =
0.5000
Aim :- Write a Function File named Cosine series to evaluate Cosine series for
given value of x & n using given formula.
Sol :-
function a=cosineseries(x)
n=input('Enter the no. of term in the expansion series');
sum=0;
for k=1:n
sum=sum+((-1)^(k-1))*(x^(2*(k-1))/factorial(2*(k-1)));
end
a=sum;
OUTPUT :-
cosineseries(pi/3)
Enter the no. of term in the expansion series5
ans =
0.5000
>> cosineseries(pi/3)
Enter the no. of term in the expansion series2
ans =
0.4517
Aim :- Write a Script File named sine series to
evaluate sine series for given value of x & n using
given formula.
Sol :- sinseries(x)
n=input('enter the number of terms in sin')
for k=1:n
sum=sum+(-1)^(k-1)*(x^(2*k -1))/(fact(2*k-1));
end
Output :_
> sinseries
enter the value of xpi/6
Enter the no. of terms in sine series
sum =
0.5000
Aim :- Write a Function File named Cosine series to
evaluate Cosine series for given value of x & n using
given formula.
Sol :-
function a=cosineseries(x)
n=input('Enter the no. of term in the expansion series');
sum=0;
for k=1:n
sum=sum+((-1)^(k-1))*(x^(2*(k-1))/factorial(2*(k-1)));
end
a=sum;
OUTPUT :-
cosineseries(pi/3)
Enter the no. of term in the expansion series5
ans =
0.5000
>> cosineseries(pi/3)
Enter the no. of term in the expansion series2
ans =
0.4517
Aim :- Make a plot of the function f(x)=sin(1/x) For 0.01<x<0.1 How did you create x so that the plot looked good. Sol :-
x=linspace(0.01,0.1,100)
y=sin(1./x)
plot(x,y)
xlabel('x value')
ylabel('y value')
output:-
0.01 0.02 0.03 0.04 0.05 0.06 0.07 0.08 0.09 0.1 0.11-1
-0.8
-0.6
-0.4
-0.2
0
0.2
0.4
0.6
0.8
1
x value
y v
alu
e
Aim :- Express plot the expression (determine in modeling the
growth of the us population)
P(t)=197273000(1+e-0.0313(t-1913.25))
Where t is the date ,in years AD,using t=1790 to 2000
Sol :-
t=(1790:2000)
p=197273000.*(1+exp(-0.0313.*(t-1913.25)))
plot(t,p);
Output :-
1750 1800 1850 1900 1950 20000
1
2
3
4
5
6
7
8
9
10x 10
9
Aim:- Write a script file to generate and write a temperature table.
SOL :_
Step 1 :-Create an m file and write following coding.
f=-40:5:100;
c=(f-32)*5/9;
t=[f;c];
fid=fopen('temparature.table','w');
fprintf(fid,'```````````````````````\n');
fprintf(fid,'Tempareture table\n');
fprintf(fid,'fahrenheit celsius\n');
fprintf(fid,'%4i %8.2f\n',t);
fclose(fid);
Step 2 :- Save script file with name temprature.m .
Step 3 :- To execute script File write filename on the window.
Output :-
> temprature
>> t
t =
Columns 1 through 11
-40.0000 -35.0000 -30.0000 -25.0000 -20.0000 -15.0000 -10.0000 -5.0000 0 5.0000 10.0000
-40.0000 -37.2222 -34.4444 -31.6667 -28.8889 -26.1111 -23.3333 -20.5556 -17.7778 -15.0000 -
12.2222
Columns 12 through 22
15.0000 20.0000 25.0000 30.0000 35.0000 40.0000 45.0000 50.0000 55.0000 60.0000
65.0000
-9.4444 -6.6667 -3.8889 -1.1111 1.6667 4.4444 7.2222 10.0000 12.7778 15.5556 18.3333
Columns 23 through 29
70.0000 75.0000 80.0000 85.0000 90.0000 95.0000 100.0000
21.1111 23.8889 26.6667 29.4444 32.2222 35.0000 37.7778
Aim :- Write A script File For keyboard command.
Sol :-
a = ones(10);
for i=1:10
disp(i)
a(:,i)=i*a(:,i);
if i==5
keyboard
end
end
Output :-
>>a =
1
2
3
4
5
K>> return
6
7
8
9
10
Aim :- Introduction to Script file and Function File .
A script file is an external file that contains a sequence of MATLAB® statements. By typing the
filename, you can obtain subsequent MATLAB input from the file. Script files have a filename
extension of .m and are often called M-files.
Scripts are the simplest kind of M-file. They are useful for automating blocks of MATLAB
commands, such as computations you have to perform repeatedly from the command line.
Scripts can operate on existing data in the workspace, or they can create new data on which to
operate. Although scripts do not return output arguments, any variables that they create
remain in the workspace, so you can use them in further computations. In addition, scripts can
produce graphical output using commands like plot.
Scripts can contain any series of MATLAB statements. They require no declarations or
begin/end delimiters.
Like any M-file, scripts can contain comments. Any text following a percent sign (%) on a given
line is comment text. Comments can appear on lines by themselves, or you can append them to
the end of any executable line.
Function File :-
A Function file is also an M file, Like a script file, except that the variable in a function file are all
local. Function files are like program or subroutines in Fortran and function in C. A function file
Begin with a function definition line, Which has a well defined list of inputs and outputs.
Aim :- Introduction To MATLAB as a calculator.
Sol :-
>> 2+2
ans =
4
>> 3-4
ans =
-1
>> 3\3
ans =
1
>> 3/4
ans =
0.7500
>> 6^7
ans =
279936
>> 3*6
ans =
18
>> sin(pi/6)
ans =
0.5000
>> cos(pi)
ans =
-1
Aim :- How to create a cell.
Sol:- cell:- A cell is most versatile data object in MATLAB. It can contain any data
type of data- an array of numbers, strings, structure,or cells. An array of cell is
called a cell array.
Creating cell arrays:- the ‘cell’ function creates empty cell arrays of the specified
size.
c=cell(2,2);
>> c(1,1)={[12 23 34; 12 67 78; 56 78 09]};
>> c(1,2)={'narendra mohan'};
>> c(2,1)={[2i,1-7i,-5]};
>> c(2,2)={['mittal','gupta','garg']}
Output :-
c =
[3x3 double] 'narendra mohan'
[1x3 double] 'mittalguptag
OUTPUT:-
After click on ‘c’ cell present on workspace window the following window appers.
Content indexing in Cells:-
In content indexing the braces are used in reverse manner. The cell indices are
put in curly braces while the cell contents are mentioned on right side of the
assignment statement .
>> c{1,1}=[12 23 34; 13 45 56; 45 67 78];
>> c{1,2}='narendra';
>> c{2,1}=1-7i;
>> c{2,2}=['mohgj','hgjgu']
c =
[3x3 double] 'narendra'
[1.0000 - 7.0000i] 'mohgjhgjgu'
>> celldisp(c) % display full cell contents.
c{1,1} =
12 23 34
13 45 56
45 67 78
c{2,1} =
1.0000 - 7.0000i
c{1,2} =
narendra
c{2,2} =
mohgjhgjgu
>>cellplot(c) % graphical display of cell architecture use cellplot.
narendra
1-7i mohgjhgjgu
Aim :- Write a script file to create a sine curve.
Coding:-
theta = linspace(0,2*pi,50)
x=theta;
y=sin(theta);
plot(x,y)
axis('equal');
xlabel('x coodinates')
ylabel('y coodinates');
title('SINE CURVE');
Output :-
0 1 2 3 4 5 6
-2
-1.5
-1
-0.5
0
0.5
1
1.5
2
x coodinates
y c
oodin
ate
s
SINE CURVE
Aim :- How to Publishing reports.
Sol:-
You can create a fancy , formatted reports in HTML, XML MS word and MS
Powerpoint using MATLAB built in publisher.
Step 1:-
Format the script as a cell script:
%% Publishing REports- A Simple Example
%% Description
% Plot a spiral
%% Create vectors theta and r
%
theta = linspace(0,10*pi,200); % 200 points between 0 & 10*pi.
r=exp(-theta/10);
%% Plot the spiral using polar plot.
polar(theta,r)
%%
% *BOLD TEXT*
Output :-
You can use the same steps to publish the report in other formats by selecting
Edit publish configuration dialog box.
If you publishing reports in Word document then Edit publish configuration
output setting Output Format : doc. AS shown in figure.
Output:-
Publishing Reports- A simple example Description ........................................................................................................................................ 35
create vectors theta and r.................................................................................................................. 35
plot spiral using polar plot ................................................................................................................. 35
Description %plot a spiral given by r=e^(theta/10),0<=theta<=10*pi
%
create vectors theta and r theta = linspace(0,10*pi,200);
r=exp(-theta/10);
plot spiral using polar plot polar(theta,r)
Aim :- Write a script File to Generate an Overlay Plots
with HOLD command.
Sol:- hold Command is used to freeze the current plot
in the graphics window.
% script file to generate an overlay plots with HOLD command.
x=linspace(0,2*pi,100); % generate vector x
y1=sin(x); % calculate vector x
plot(x,y1) % plot(x,y1) with solid line
hold on % invoke hold for overlay plots
y2 = x;
plot(x,y2,'--') % plot(x,y2) with solid line.
y3=x-(x.^3)/6 + (x.^5)/120;
plot(x,y3,'o')
axis([0 5 -1 5])
hold off
OUTPUT:-
0 1 2 3 4 5 6 7-1
-0.8
-0.6
-0.4
-0.2
0
0.2
0.4
0.6
0.8
1
Aim :- Generate Overlay plots using plot command.
Sol:- Plot command is used to providing more argument to generate more plots in
the same graphic window.
t=linspace(0,2*pi,100);
y1=sin(t);
y2=t;
y3=t-(t.^3)/6 + (t.^5)/120;
plot(t,y1,t,y2,'d',t,y3,'o')
axis([0 5 -1 5])
xlabel('t')
ylabel('Approxim,ation of sin(t)')
text(3.5,0,'sin(t)')
gtext('linear approxmation'
OUTPUT:-