Вы находитесь на странице: 1из 75

BASICS OF MATLAB

BUILDING BLOCKS OF A SCRIPT FILE


WORKSPACE WINDOW
SCRIPT COMMANDS
BEFORE WORKING ON A SCRIPT, FOLLOWING POINTS NEED TO BE
REMEMBERED:
1. EXTENSION FOR THE SCRIPT FILE IS “.m”
2. MATLAB CANNOT ASSUME ANY VALUE TO A VARIABLE ON ITS
OWN AND NEEDS TO BE DEFINED
3. THE ENTIRE PROGRAM IS EDITABLE
4. BEFORE EXECUTING THE SCRIPT FILE, IT HAS TO BE SAVED
FIRST.
5. TO RUN A FILE AFTER SAVING, PRESS THE RUN ICON ON THE
TOOLBAR. THE SHORTCUT FOR EXECUTING A FILE “F5”
6. THE RULES FOR NAMING A SCRIPT FILE FOLLOW THE RULES
OF NAMING A VARIABLE I.E. MUST BEGIN WITH A LETTER,
CAN INCLUDE DIGITS AND UNDERSCORE, AND BE UPTO 63
CHARACTERS LONG.
VARIABLES
 A SYMBOL WHOSE VALUE CAN BE CHANGED
 3 WAYS TO INPUT A VARIABLE IN MATLAB
 ASSIGNING A VALUE IN THE SCRIPT
 ASSIGNING A VALUE IN THE COMMAND WINDOW
 ASSIGNING A SPECIFIED VALUE WHEN PROMPTED
IN COMMAND WINDOW AFTER EXECUTING THE
SCRIPT FILE.
AFTER EXECUTION
 OUTPUT COMMANDS
 “disp”- TO DISPLAY THE OUTPUT
 “fprint” – TO DISPLAY THE OUTPUT AS A MIX OF TEXT AND
DATA.

 LOAD AND SAVE COMMANDS


 “load”- TO LOAD THE WORKSPACE IN ANOTHER PLATFORM
 “save”-TO SAVE THE CURRENT WORKSPACE
Example for using display command
IMPORTING AND EXPORTING
 IMPORTING FROM MS-EXCEL TO MATLAB
 “xlsread”
 EXPORTING FROM MATLAB TO MS-EXCEL
 “xlswrite”
PLOTS ON MATLAB
TWO-DIMENSIONAL PLOTS
TWO TYPES OF PLOT COMMANDS: FORMATING A GRAPH:
1. “plot”-SIMPLEST PLOT COMMAND  “line specifiers”
2. “fplot”-PLOTS ANY FUNCTION  “line color specifiers”

 “marker type specifiers”

 “property name”

 “property value”
PLOTTING MULTIPLE GRAPHS
1. “hold on” AND “hold off ”
2. TYPING IN PAIRS
3. “line”
FORMATING A PLOT:
1. “xlabel” AND “ylabel”
2. “title”
3. “legend”
4. “grid on” AND “grid off ”
5. PLOT EDITOR
PLOTS WITH SPECIAL GRAPHICS
HISTOGRAMS
POLAR PLOTS
PROGRAMMING IN
MATLAB
RELATIONAL AND LOGICAL OPERATOR
ORDER OF PRECEDENCE
Built in logical Description
functions
xor(a,b) Exclusive or. Returns true (1) if one operand is true and the
other is false.
all(A) Returns 1 (true) if all elements in a vector A are true
(nonzero).
Returns 0 (false) if one or more elements are false (zero).
If A is a matrix, treats columns of A as vectors, and returns a
vector with 1s and 0s.

any(A) Returns 1 (true) if any element in a vector A is true (nonzero).


Returns 0 (false) if all elements are false (zero).
If A is a matrix, treats columns of A as vectors, and returns a
vector with 1s and 0s.

find(A) If A is a vector, returns the indices of the nonzero elements.


If A is a vector, returns the address of the elements that are
find(A>d)
larger than d (any relational operator can be used).
CONDITIONAL STATEMENTS AND LOOPS

“ if ” Statement
“ if-end ” Structure
 “ if-else-end ” Structure
 “ if-elseif-else-end ” Structure
“ switch-case ” Statement
 “ for-end ” Loops
 “ while-end ” Loops
THE “IF-END” STRUCTURE
Problem
A worker is paid according to his hourly wage up to 40
hours, and 50% more for overtime.
Write a program in a script file that calculates the pay
to a worker. The program asks the user to enter the
number of hours and the hourly wage. The program
then displays the pay.
Problem
A worker is paid according to his hourly wage up to 40
hours, and 50% more for overtime.
Write a program in a script file that calculates the pay
to a worker. The program asks the user to enter the
number of hours and the hourly wage. The program
then displays the pay.
Solution
t=input('Please enter the number of hours worked ');
h=input('Please enter the hourly wage in Rs. ');
Pay=t*h;
if t>40
Pay=Pay+(t-40)*0.5*h;
end
fprintf('The worker''s pay is Rs. %5.2f',Pay)
THE “IF-ELSE-END” STRUCTURE
Problem
A worker is paid according to his hourly wage up to 40 hours, and
if he works for more than that he will be paid 1.5 time of hourly
wage.
Write a program in a script file that calculates the pay to a
worker. The program asks the user to enter the number of hours
and the hourly wage. The program then displays the pay.
Problem
A worker is paid according to his hourly wage up to 40 hours, and
if he works for more than that he will be paid 1.5 time of hourly
wage.
Write a program in a script file that calculates the pay to a
worker. The program asks the user to enter the number of hours
and the hourly wage. The program then displays the pay.

Solution
t=input('Please enter the number of hours worked ');
h=input('Please enter the hourly wage in Rs. ');
if t<=40
Pay=t*h;
else
Pay=t*1.5*h;
end
fprintf('The worker''s pay is Rs. %5.2f',Pay)
THE “IF-ELSEIF-ELSE-END” STRUCTURE
Problem
Using a MATLAB program for Analog/Digital
converter (if else) where ‘x’ is input and ‘y’ is digital
output governed by following eq.
y =0 x<-2.5
=1 -2.5<x<-1.5
=2 -1.5<x<-0.5
=3 -0.5<x<0.5
=4 0.5<x<1.5
=5 1.5<x<2.5
=6 2.5<x<3.5
=7 x>3.5
Test for condition with amplitudes -1.25, 2.57 and 6.
Solution
x_analog =input('Please enter the number ');
if x_analog<-2.5
y_dig=0
elseif x_analog>=-2.5 & x_analog<-1.5
y_dig=1
elseif x_analog>=-1.5 & x_analog<-0.5
y_dig=2
…….(so on)
elseif x_analog>=2.5 & x_analog<3.5
y_dig=6
else y_dig=7
end
“SWITCH-CASE” STATEMENT
grade = input(‘enter the grade‘,’s’);
switch(grade)
case 'A'
fprintf('Excellent!\n’ );
fprintf('Your Grade is A\n');
case 'B'
fprintf('Well done\n' );
fprintf('Your Grade is B\n');
case ‘C'
fprintf('You passed\n' );
fprintf('Your Grade is C\n');
case 'F'
fprintf('Better try again\n’ );
fprintf('Your Grade is F\n');
otherwise
fprintf('Invalid grade\n' );
end
Problem
Using a MATLAB program classify article in one of the
three categories named as fruit, game, utensil. If article
does not belong to any of these three category classify
it as an unknown article.
Problem
Using a MATLAB program classify article in one of the
three categories named as fruit, game, utensil. If article
does not belong to any of these three category classify
it as an unknown article.
Solution
article = input(‘ ___ ’,’s’);
switch article
case {'orange', 'apple', 'guava', 'banana', 'pomegranate'}
disp('Article is fruit')
case {'chess', 'carrom', 'ludo'}
disp('Article is game')
case {'spoon', 'fork', 'cup', 'saucer'}
disp('Article is utensil')
otherwise
disp('Unknown article.')
end
TUTORIAL PROBLEMS
1. Write a script file that takes a vector input and returns 1 if all of the
elements are positive, −1 if they are all negative, and zero for all other
cases.
2. The tank in a water has the geometry shown in figure (the lower part is a
cylinder and the upper part is an inverted frustum cone). Inside the tank
there is a float that indicates the level of the water. Write a MATLAB
scriipt file that determines the volume of the water in the tank from the
position (height h ) of the float. The input to the program is the value of
h in m, and the output is the volume of the water in m3.
3. Write a program in a script file that converts a quantity of energy (work)
given in units of either joule, ft-lb, cal, or eV to the equivalent quantity in
different units specified by the user. The program asks the user to enter the
quantity of energy, its current units, and the desired new units. The
output is the quantity of energy in the new units.
The conversion factors are: 1 J = 0.738 ft-lb = 0.239 cal = 6.24 x 1018 eV.
Use the program to:
(a) Convert 150 J to ft-lb.
(b) Convert 2,800 cal to J.
(c) Convert 2.7 eV to cal.
4. At an institute office, there are employees with the following ages:

5. Write a program that takes age and number of employees as input and
returns average age.
5. Write a script that uses input(...) to request a numerical grade in
percentage and uses if statements to convert that grade to a letter grade
according to the following table:
90% and better: A
80%–90%: B
70%–80%: C
60%–70%: D
Below 60%: F
6. Write a script that uses input(...) to request a numerical month value and
determine the number of days in a month.
LOOPS
 Execution of a command, or a group of commands, is repeated
several times consecutively.
 Each round of execution is called a pass.
 Two kinds of LOOPS:
 For-loops - the number of passes is specified when the loop starts.
 While-loops - the number of passes is not known ahead of time, and
the looping process continues until a specified condition is satisfied.
 Both kinds of loops can be terminated at any time with the
“break” command.
FOR LOOP
for index = m:n:p
statements
end
A few rules to keep in mind when using for loops:
1. The step value n can be negative. For example k = 20:-4:4 produces k =
20, 16, 12, 8, 4.
2. If n is omitted, the increment value defaults to 1.
3. If n is positive, the loop will not be executed if m is greater than p.
4. If n is negative, the loop will not be executed if m is less than p.
5. If m = p, the loop will be executed once.
6. The loop index variable can have any variable name (usually i, j, k, m, and
n are used, however, i and j should not be used if MATLAB is used with
complex numbers).
Let's write a program that will calculate and plot the sum of n terms of this equation
for t between -1.1 and 1.1 in steps of say, 0.01.
%Inputs are n, the number of terms in the Fourier series.
%Output is the plot of those n terms added together.

Steps of Constructing the program :-

1. Input the number of terms k in the series.

2. Initialise the sum.

3. Define the interval we will plot over.

4. plot(t,f).
 n = input('Enter an integer less than 200 for the number of
terms in the Fourier series: ');
 h = 0; %Initialising the sum
 for t = -1.1:0.01:1.1 % Defining the array
 h = h + 1; % Sum Increment
 f(h) = 0; % Total Sum Initialisation
 for k = 0:n-1; % Defining the number of terms
 f(h) = f(h) + 1/(2*k+1)*sin((2*k+1)*pi*t);
 end
 end
 t = -1.1:0.01:1.1;
 plot(t,f)
WHILE LOOP
while conditional expression
statements
end

A few rules to keep in mind when using while loops:


1. The conditional expression in the while command must include at least
one variable.
2. The variables in the conditional expression must have assigned values
when MATLAB executes the while command for the first time.
3. At least one of the variables in the conditional expression must be
assigned a new value in the commands that are between the while and the
end. Otherwise, once the looping starts it will never stop since the
conditional expression will remain true.
Let’s calculate the value exp(x) by adding the terms of the series and stopping when the
absolute value of the term that was added last is smaller than 0.0001, but limit the
number of passes to 30. Use the program to calculate the value of exp(2), exp(-4) and
exp (21).
% Inputs are n, the number of terms in Taylor series.

Steps of constructing the Program :-


1. Initialise the number of terms and sum.
2. Form the conditional statement for the loop.
3. Define the loop.
4. Using “if ” conditions, limit the number of terms to 30.
x=input('Enter x ' );
n=1; an=1; S=an;
while abs(an) >= 0.0001 & n <= 30
 an=x^n/factorial(n);
 S=S+an;
 n=n+1;
end
if n >= 30
 disp('More than 30 terms are needed')
else
fprintf('exp(%i) = %f',x,S)
fprintf('\nThe number of terms used is: %i',n)
end
NESTED LOOP AND NESTED CONDITIONAL
STATEMENTS

It must be remembered that for each “if, case, for, and while
statement”, there must have a corresponding “end” statement.
CREATING A MATRIX WITH NESTED LOOP

Write a program in a script file that creates an n x m matrix


with elements that have the following values. The value of each
element in the first row is the number of the column. The value
of each element in the first column is the number of the row.
The rest of the elements each has a value equal to the sum of
the element above it and the element to the left. When
executed, the program asks the user to enter values for n and
m.
OTHER IMPORTANT COMMANDS

BREAK CONTINUE
 When inside a loop (for or  The continue command can
while), the break command be used inside a loop (for or
terminates the execution of while) to stop the present
the loop (the whole loop, not pass and start the next pass
just the last pass). in the looping process.
 If the break command is  The continue command is
inside a nested loop, only the usually a part of a
nested loop is terminated. conditional statement. When
 When a break command MATLAB reaches the
appears outside a loop in a continue command, it does
script or function file, it not execute the remaining
terminates the execution of commands in the loop, but
the file. skips to the end command of
the loop and then starts a
new pass.
APPLICATIONS IN NUMERICAL ANALYSIS

Solving an Equation with one variable


FINDING A MINIMUM OR A MAXIMUM OF A FUNCTION
NUMERICAL INTEGRATION

3 METHODS TO PERFORM INTEGRATION :-


1. quad (Adaptive Simpson Method)
2. quadl (Adaptive Lobatto Method)
3. Trapz

 The first two methods are used when f(x) is a function whereas trapz is used when
f(x) is given by data points.
ORDINARY DIFFERENTIAL EQUATION

SELECTING A METHOD OF SOLUTION


The solvers can be divided into two groups according to their ability to solve stiff
problems and according to whether they use on-step or multistep methods.
1. Stiff problems are ones that include fast and slowly changing components and
require small time steps in their solution.
2. One-step solvers use information from one point to obtain a solution at the next
point.
3. Multistep solvers use information from several previous points to find the solution at
the next point.

%%The details of the different methods are beyond the scope of this book.%%
[t,y] = ode45((t^3-2*y)/t,[1:0.5:3], 4.2)
ASSIGNMENT
6.Following data points are the daily maximum and
temperature(in C) of Jabalpur , during the month of
September 2016
Day 1 2 3 4 5 6 7 8
9 10 11 12 13 14 15 16
17 18 19 20 21 22 23 24
25
Min 24 25 23 24 23 23 24 26
25 25 24 22 22 21 22 25
26 26 23 23 24 23 22 22
22
Max 32 30 31 31 31 31 30 32
32 32 32 33 32 32 32 32
34 33 32 33 32 32 32 31
29

Plot a graph, showing the temperature distribution during


the month and plot a histogram which represents the
occurrence of temperature.
12. Use matrix operations to solve the following system of linear
equations.
4x – 2y + 6z = 8
2x + 8y + 2z = 4
6x + 10y + 3z = 0

13. A cylindrical silo with radius r has a spherical cap roof with radius
R. The height of the cylindrical portion is H. Write a program in a
script file that determines the height H for given values of r, R,
and the volume V. In addition, the program calculates the surface
area of the silo. Use the program to calculate the height and
surface area of a silo with r = 30 ft, R = 45 ft, and a volume of
120,000 ft3. Assign values for r, R, and V in the Command
Window.

Вам также может понравиться