Chapter 1n

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 50

Engr 105: Engineering and

Computing Skills

Author

image here
Chapter 1: Introduction to Matlab
Chapter 2: Algorithmic Structures in
MATLAB
Chapter 3: Mathematical Applications in
MATLAB
Outline
Chapter 4: Polar Coordinates in MATLAB &
Integration Using Polar Coordinates
Chapter 5: Definite and Indefinite Integrals
Chapter 6: Symbolic Math in MATLAB
Chapter 1: Introduction to Matlab

Author

image here
Introduction
Matlab for Windows
Variables
Matlab as a Calculator
Constants and Math Functions
Outline Display Function & Formats
Plots
Programming in Matlab
Scripts
Functions
Matlab
A program for doing numerical computation. Originally
designed for solving linear algebra type problems
using matrices.

5
Display Windows

6
Matlab GUI

Desktop menus
File menu
New
Create new Matlab program file (m-
file)
Open existing m-file
Import data
Set path
Open recent m-files

7
MATLAB GUI
Edit Menu
Copy, cut, paste
Find and replace
phrases
Clear command
history, workspace
Desktop Menu
Change appearance of
desktop
Select windows to
display

8
Getting Help

type one of following commands in the command window:


help  lists all the help topic
help command  provides help for the specified command
Example:
>> help sqrt
SQRT Square root.
SQRT(X) is the square root of the elements of X. Complex
results are produced if X is not positive.
help help  provides information on the help command use

9
Arithmetic Operators in MATLAB

The contents of all bracketed expressions are evaluated, starting from the
innermost brackets and working out.
All exponentials are evaluated, working from left to right.
All multiplications and divisions are evaluated, working from left to right.
All additions and subtractions are evaluated, working from left to right.
Operators:
+ for addition
- For subtraction
* for multiplication
/ for division
^ for power
10
Operator Precedence

Precedence is the order in which operations are performed.


(Highest) Parenthesis . anything in parenthesis is done first
Exponentiation
Multiplication, division
(Lowest) Addition, subtraction
Spaces are ignored
Solve the following examples:
>> 2 + 3 * 4
>> 2 * 3 ^ 2
>> (2 + 3) * 4
>> (2^(2 + 3)) * 4 11
Variables

Variables are named memory locations that can be assigned a


value by the user or programmer.
The system can retrieve , or “remember” the value of a variable.
Variable names:
Must start with a letter
May contain only letters, digits, and the underscore “_”
Matlab is case sensitive, i.e. one & OnE are different variables.
Assignment statement:
Variable = number; NOTE: when a semi-colon ”;” is placed at
Variable = expression; the end of each command, the result is not
displayed. 12
Matlab always perform matrix calculations
Variable is not single value but a matrix.
A single valued variable is stored as matrix of 1x1.
All calculations are performed as matrix operations.

Working in command window and editor window examples

13
Variable Examples

>> tutorial = 1234;


>> tutorial = 1234
tutorial = ?
>> a  ??? Undefined function or variable 'a'.
>> a=2 a=?
>> a+3 ans = ?
>> sqrt(a+14) ans = ?
>> a=a+12 a= ?

14
Exercise

Use command window


A=5
B=34
C=-98;
D=
B=B+D

15
String Variables

>> a = 'This is a string'


a=?
>> b= 'Another string'
b=?

>> a + b
 ??? Error using ==> plus Matrix dimensions must agree.

16
Special Variables

ans : default variable name for the result


pi: π = 3.1415926…………
eps: ԑ = 2.2204e-016, smallest amount by which 2 numbers can
differ.
Inf or inf : ∞, infinity
NaN or nan: not-a-number

17
Defining Symbolic Variables & Viewing Variables

Use sym to create a symbolic variable x:


Use syms to create several symbolic variables at one time
Use who to view all variables in the workspace
» x=sym('x');
» syms y a b
» who
Your variables are:

Use whos to view all workspace variables with their associated


size, bytes, and class information
» n=1.0;t=[1.1 2.2 3.3];
» whos
18
Symbolic Expressions

Symbolic expressions are expressions that contain symbolic


variables
Example:
» f = 2*x^2 + x + 1;
» g = a*x^2 + b*x + 5
g =?

19
MATLAB as a Calculator

MATLAB can be used as an expression evaluator.


For example, to “evaluate” pi type
>> pi
ans = ?
x=pi % the value of pi is assigned to variable x
Try the following examples:
>> r = sqrt(9)
r=?
>> m = sin(pi/2)
m=?
20
Constants and Functions

>> eps
ans = 2.2204e-016
>> sin(pi/2)
ans = 1
>> log(1000)
ans = 6.9078
>> log10(1000)
ans = 3

21
Elementary Math Functions

>> help elfun


Elementary math functions.
Trigonometric.
sin - Sine.
sinh - Hyperbolic sine.
asin - Inverse sine.
asinh - Inverse hyperbolic sine.
cos - Cosine.
cosh - Hyperbolic cosine.
acos - Inverse cosine.
acosh - Inverse hyperbolic cosine.
tan - Tangent.
tanh - Hyperbolic tangent.
atan - Inverse tangent.
atan2 - Four quadrant inverse tangent
atanh - Inverse hyperbolic tangent.
sec - Secant.
sech - Hyperbolic secant.
asec - Inverse secant.
asech - Inverse hyperbolic secant.
csc - Cosecant.
csch - Hyperbolic cosecant.
acsc - Inverse cosecant.
acsch - Inverse hyperbolic cosecant.
cot - Cotangent.
coth - Hyperbolic cotangent.
acot - Inverse cotangent.
acoth - Inverse hyperbolic cotangent. 22
Elementary Math Functions

exp Exponential (e^x).


log Natural logarithm.
log10 Common (base 10) logarithm.
log2 Base 2 logarithm and dissect floating point number.
sqrt Square root.
Exponential function examples:
>> exp(log(3))
>> log(exp(3))
>> log2(32)
>> log2(pow2(5)) 23
Elementary Math Functions

Rounding and remainder


fix Round towards zero.
floor Round towards minus infinity.
ceil Round towards plus infinity.
round Round towards nearest integer.
mod Modulus (signed remainder after division).
rem Remainder after division.
sign Signum (Returns 1 if x>0;-1 if x<0; 0 if x=0).

24
Rounding Examples
+ -
round(2.7) = ? round(-2.7) = ?
round(2.3) = ? round(-2.3) = ?
fix(2.3) = ? fix(-2.3) = ?
fix(2.7) =? fix(-2.7) = ?
ceil(2.3) = ? ceil(-2.3) = ?
ceil(2.7) = ? ceil(-2.7) = ?
floor(2.3) = ? floor(-2.3) = ?
floor(2.7) = ? floor(-2.7) = ?
rem(13,5) = ? rem(13,5) = ?

25
Mathematical Functions in MATLAB

Some of the Matlab built-in functions are:


abs(x) for absolute value
sqrt (x) for square root
sin(x) for sine
cos(x) for cosine
tan(x) for tangent
cot(x) for cotangent
log(x) for natural logarithm
exp(x) for exponentioal
atan(x) for inverse tangent or arctan
sinh(x) for sine hyperbolic
26
disp Function

Used to display numbers and strings.


The values displayed at the screen don’t necessarily include all the
information.
It is possible to change the display format.
Examples
>> disp(3)  3
>> disp('abc')  abc
>> format long
>> pi  ans = ?
>> format short
>> pi  ans = ? 27
fprintf Function

Advanced version of the disp function


Displays text and variables simultaneously
C++ principles based
Syntax: fprintf(‘text %var1_place_type text’, var1_name)
Example:
a=65;
b=97;
fprintf('the sum of %i and %i is %i',a,b,a+b)
fprintf('the ASCII code of %s is %i',a,a)

28
fprintf arguments

Type of variables:
%i: integer
%d: double
%f: float
%c: char
%s: string
Possibility to control the number of decimal places
Ex: fprintf(‘a with three decimal places: %.3f',a)
Ex: fprintf('a with 4 numbers: %.4i',a)
All the text in the same line? Use \n for a new line
29
Drawing in MATLAB

Possibility to draw figures and curves in MATLAB


The x axis limit need to be specified most of the time
 ex: x= -6 : 0.1 : 6
Different plot types:
Plot: draw the curve of an equation that depends on a variable
Ezplot: plot with a predefined range of [-2π, 2π]
Subplot: draw many plot in the same window
Figure: create a separate window for a new plot
Ex: syms x
ezplot(sin(x))
figure
ezplot(cos(x)) 30
plot Command Syntax

Plot(x,y,’r’): plot x in function of y with the ‘r’ (red style)


‘r’: red ‘b’:blue ‘black’: black
‘x’: cross ‘o’: circle ‘.’: Points
plot(x,y1,'--',x,y2,'-',x,y3,':')  plot multiple plots
xlabel(‘name'):  give a name to X-axis
ylabel(‘name'):  give a name to Y-axis
legend(‘y1',‘y2',‘y2')  display each plot’s
legend
title(‘name')  display the plot title
axis([0 2*pi -3 3]):  define the X & Y axis
limits 31
Plotting Symbolic Function

In Matlab, we can plot a symbolic function over one variable by using the
ezplot function.

>> syms a b c x % define symbolic math variables


>> y = sin(x)

>> ezplot(y)
>> f = sin(x);
>> ezsurf(f) % another type of plotting example

>> g = cos(y);
>> ezsurf(f+g);

32
subplot Command

Draw multiple independent plots in the same window


Syntax: subplot(x,y,id)

syms x
subplot(2,2,1)
ezplot(cos(x))

subplot(2,2,2)
ezplot(sin(x))

subplot(2,2,3)
ezplot(tan(x))

subplot(2,2,4)
ezplot(atan(x)) 33
Programming in MATLAB
Script and Functions: Script Files

A user-created file with a sequence of MATLAB commands in it.


A text file containing script or function or program to run
The file must be saved with a ‘.m’ extension to its name, thereby,
making it an M-file.
Executed by typing its name (without the ‘.m’ extension) at the
command prompt.

35
Create a .m File

From the File menu, select New → M-File.


A new edit window should appear.

36
Example 1 Example 1:
in m-file: in Command window

A= 2; >> example1
B=3;
C=A+B C = ?

Save as a file name example1.m

37
Example 2

Find the force if the mass is 10 Kg and the acceleration is 100m/sec2.


Newton’s Law: F = m .γ (Force = mass x acceleration) (a = 100)

Create a new script (example2.m)

m = 10;
a = 100;
Force =m * a

To run the above file, type in the command window


>>example2
38
Script and Functions: Function Files

A m-file also , like a script file, except that the variables are all local.
A function file begins with a function definition line containing a well-
defined list of inputs and outputs.
Without that line, the file becomes a simple script file.
The syntax of the function definition line is:
function [ output variables ] = function_name ( input
variables );
It is recommended for the function_name to be the same as the
filename (without the ‘.m’ extension) in which the function is written.
Example: if the name of the function is projectile it must be written
and saved in a file with the name projectile.m.
39
WARNING!
for the scipt or function name
file, avoid using the name of
a MATLAB command such as
plot, sqrt, abs…
Example 3

Write a MATLAB function called sumy that adds two input numbers and
returns the result minus 2

function out = sumy(x,y)


out=x+y-2

Save with filename sumy.m , then type in the command window:

>>sumy(6,5) % 6 and 5 are arbitrary values chosen by the user


out = ?

41
Example 3: Measuring a Solid Object Solution
Function file:
We need to compute the volume and function [area, volume] = cyl(h, r)
surface area of this cylinder object: % function to compute the area and volume of a cylinder

base = pi * r^2;
volume = base * h
area = 2*pi*r * h + 2*base

Store the function in cyl.m, then, in


command window:
Formulas: b: base, h: height >> cyl(6, 4)
area = ?
Base: b= π r² vol = ?
Volume = b h
Area=2 π r h + 2 b

42
Exercises
Example 1: Create a m-file and enter the
Consider the system of equations: following statements in the m-file:
x + 2y + 3z = 1
A = [1 2 3; 3 3 4; 2 3 3];
3x + 3y + 4z = 1
b = [1; 1; 2];
2x + 3y + 3z = 2
x = A\b
Find the solution x to the system of
equations.
Save the file, (e.g. example1.m)
In the command line, type:
>> example1
x = ?

44
Example 2: Create a file, say example2.m,
Plot the following cosine functions, which contains the following
y1 = 2 cos(x) commands:
y2 = cos(x)
x = 0:pi/100:2*pi;
y3 = 0.5 * cos(x)
y1 = 2*cos(x);
in the interval 0  x  2. y2 = cos(x);
y3 = 0.5*cos(x);
plot(x,y1,'--',x,y2,'-',x,y3,':')
xlabel('Range')
ylabel('Cosine functions')
legend('2*cos(x)','cos(x)','0.5*cos(x)')
title('Example of multiple plots')
axis([0 2*pi -3 3])

Run the file by typing example2 in


the Command Window. 45
Example 3: game1 = input('Enter the points
scored in the first game ');
Create a script file that calculates
game2 = input('Enter the points
the average of points scored in scored in the second game ');
three games.
game3 = input('Enter the points
The point from each game are scored in the third game ');
assigned to a variable by using the average = (game1+game2+game3)/3
’input’ command.

The following shows the command


prompt when this script file (saved
as example3) is executed.
>> example3
>> Enter the points scored in the
first game xx
>> Enter the points scored in the
second game yy
>> Enter the points scored in the
third game zz
average = ? 46
Example 4

Create a script in a file computes area of triangle

b=5;
h=3;
area=0.5*(b*h)

area = ?

47
Scripts VS Functions

To calculate the area of another triangle using the same script, it is


possible to update the values of b and h in the script and re-run it.
the script stores the result each time in a variable named a that is in
the base workspace.
Instead of manually updating the script each time, it is possible to
make a more flexible program by converting the script to a function.
Replace the statements that assign values to b and h with a
function declaration statement.
The declaration includes
the function keyword
the names of input and output arguments
the name of the function.
48
Example 5

Redo example 4 using the function method

function a = triarea(b,h)
a = 0.5*(b.* h);
After saving the file, call the function with different values
a1 = triarea(1,5)
a1 = ?
a2 = triarea(2,10)
a2= ?
a3 = triarea(3,6)
a3= ?
49
Functions have their own
workspace (local), separate from
the base workspace (global). So,
none of the calls to the function
triarea overwrite the value of a in
the base workspace. Instead, the
function assigns the results to
variables a1, a2, and a3.

You might also like