0% found this document useful (0 votes)
19 views73 pages

CSE1121 Chapter2

Uploaded by

Taha Misirli
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views73 pages

CSE1121 Chapter2

Uploaded by

Taha Misirli
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 73

CSE 1121

Scientific Programming

ENGR 101
Introduction to Programming
Introduction to MATLAB, Variables
Command Window

• Similar to a scratch pad


• Once you hitCommand
enter,Window
you can’t edit
any commands
• You can retype them or use the
arrow keys to retrieve commands
and edit them before hitting enter
again
Command History

• You can transfer commands from the command history to


the command window
• Double click on a command
or
• Click on a command, and then hit Enter
• It executes immediately

• Click and drag into the command window


• You can edit the command before executing
Command reuse and editing

• Press the up arrow cursor key (↑) to scrolls


backward through previous commands. Press
Enter to execute the selected command.
 The down arrow cursor key (↓) scrolls forward
through commands
 The left (←) and right arrow (→) cursor keys
move within a command at the Matlab prompt,
allowing the command to be edited.
 The mouse can also be used to reposition the
command cursor, by positioning the mouse
cursor and pressing the left mouse button.
Command reuse and editing

• Other standard editing keys, such as delete


Del , backspace BkSp , home Home , and end
End , perform their commonly assigned tasks.
• Once a scrolled or edited command is
acceptable, pressing Enter with the cursor
anywhere in the command tells Matlab to
process it.
• Escape key Esc erases the current command
at the prompt.
• Windows copy and paste operations can be
used
Workspace Window

Workspace Window
When you define variables in the
command window, they are listed
in the workspace window
Scalar

Vector

2-D
Matrix
Commands for managing the work
session
who: lists the names of defined variables
whos: lists the names and sizes of defined variables

clear: clears all variables, resets default values of


special variables
clear var: clears variable var
clc: clears the command window, homes the cursor
(moves the prompt to the top line), but does not affect
variables.
clf: clears the current figure and thus clears the graph
window.
Commands for managing the work
session
: Colon; generates an array having regularly
spaced elements.
, Comma; separates elements of an array
(optional); also you can write multiple commands on the
same line by separating with comma
; Semicolon; suppresses screen printing; also
denotes a new row in an array.
… Ellipsis; continues a line. Put ellipsis to a long line
to continue it on the next line
Variables

• MATLAB allows you to assign a value to a variable


• A=3
• Should be read as A is assigned a value of 3
• Use the variables in subsequent calculations
Variables and Assignment Statements
Assignment statement:
variable = number
variable = expression
variable = input(‘enter a number’)
Variable names
1. Must start with a letter
2. May consist only of the letters a-z, digits 0-9, and the
underscore character (_)
3. May be as long as you would like, but Matlab only
recognizes the first 63 characters
4. case sensitive: items, Items, itEms, and ITEMS are all
different variable names.
Use the iskeyword function for a list of
keywords

iskeyword

ans =
'break' 'global'
'case' 'if'
'catch' 'otherwise'
'classdef' 'parfor'
'continue' 'persistent'
'else' 'return‘
'elseif' ‘spmd’
'end‘ 'switch'
'for‘ 'try'
'function' 'while'

Keywords are not acceptable variable names


Practice Exercise 2.2
Which of these names are allowed in MATLAB?

• test
• Test
• if x
• my-book x
• my_book
• Thisisoneverylongnamebutisitstillallowed? x
• 1stgroup x
• group_one
• zzaAbc
• z34wAwy?12# x
• sin bad
• log idea >>which sin
Special variables and constants
Variables and Assignment Statements

Example:
>> mterm = 60
>> final=80;
>> quiz=60
>> grade = 0.5*mterm+0.1*quiz+0.4*final
• Variables: mterm,final,quiz,grade
• Results displayed and stored by variable name
• Semicolon at the end of a line (as in the line
>> final=80;) tells Matlab to evaluate the line
but not to display the results
Variables and Assignment Statements

Examples more…
>> x=5;
>> y=x+5;
>> x=2;
y is still 10 not 7 you have to run >> y=x+5 again to obtain
new value of y.
>> z=z+2 is a correct assignment in MATLAB.

If you have not supplied a value for xx, Matlab will return a
syntax error:
>> y=xx+5
??? Undefined function or variable ’xx’.
a\b
Operators
Try following operations:

>> 3 + 5 + 2
>> 4*22 + 6*48 + 2*82
>> 4 * 4 * 4
>> 4^3
>> 56/8
>> 8\56
Numbers
Matlab represents numbers in two form, fixed point and floating
point.
Fixed point: Decimal form, with an optional decimal point.
For example: 2.6349 -381 0.00023
Floating point: Scientific notation, representing m x 10e
For example: 2.6349 x 105 is represented as 2.6349e5
The number has two parts:
 mantissa m: fixed point number (signed or unsigned), with an
optional decimal point (2.6349 in the example above)
 exponent e: an integer exponent (signed or unsigned) (5 in
the example).
Mantissa and exponent must be separated by the letter e (or
E).
Precedence of operations (order of evaluation)

There are rules about the order of operations


1. Parentheses, innermost first
2. Exponentiation (^), left to right
3. Multiplication (*) and division (/ or \) with equal
precedence, left to right
4. Addition (+) and subtraction (−) with equal
precedence, left to right
When operators in an expression have the same
precedence the operations are carried out from
left
to right. Thus 3 / 4 * 5 is evaluated as ( 3 / 4 ) * 5
and not as 3 / ( 4 * 5 ) .
Examples of Precedence

>> 8 + 3*5 >> 3*4^2 + 5


ans = ans =
23 53
>> 8 + (3*5) >>(3*4)^2 + 5
ans = ans =
23 149
>>(8 + 3)*5 >>27^(1/3) + 32^(0.2)
ans = ans =
55 5
>>4^2­-12-­
8/4*2 >>27^(1/3) + 32^0.2
ans = ans =
0 5
>>4^2­-12-­
8/(4*2) >>27^1/3 + 32^0.2
ans = ans =
3 11
1-6
Parentheses

• Use only ( )
• { } and [ ] mean something different
• MATLAB does not assume operators

5 * (3+4) not 5(3+4)


Precedence of operations (order of evaluation)


Variables and Assignment
Statements
Examples more…

TC=5/9*(TF-32)

Sometimes writing an equation in multiple statements makes the equation


more understandable

numerator = s^2 + 4*s + 13;


denominator = s^3 - 2*s^2 + 4*s + 5;
H = numerator/denominator;
Example - Solving for quadratic roots
2s2 + 10s + 12 = 0
find roots of the quadratic equation.

>> a =2;
>> b =10;
>> c =12;
>> disc = b^2-4*a*c;
>> x1 = (-b + sqrt(disc)) /(2*a)
>> x2 = (-b - sqrt(disc)) /(2*a)

x1 =

-2
x2 =

-3
Array Operations
• Using MATLAB as a glorified calculator is fine, but its real
strength is in matrix manipulations.
Matrices in MATLAB
The basic data type
• Group of numbers arranged into rows and columns
• Single Value (Scalar)
• Matrix with one row and one column
• Vector (One dimensional matrix)
• One row or one column
• Matrix (Two dimensional)
To create a row vector, enclose a list of values
in brackets
You may use either a space or a
comma as a “delimiter” in a row
vector
Use a semicolon as a delimiter to create a
new row
Use a semicolon as a delimiter to create a
new row
Hint: It’s easier to keep track of how many
values you’ve entered into a matrix, if you
enter each row on a separate line. The
semicolons are optional
Shortcuts to setup matrices

• While a complicated matrix might have to be entered by


hand, evenly spaced matrices can be entered much more
readily. The command

b= 1:5

or the command

b = [1:5]

both return a row matrix


The default increment is 1, but if you
want to use a different increment put
it between the first and final values
To calculate spacing between
elements use…

• linspace()
• logspace()
number of elements in
the array
Initial value in the
Final value in the
array
array

The increment is computed


internally, having the value:
number of elements in
the array
Initial value in the
array expressed Final value in the
as a power of 10 array expressed
as a power of 10
It is a common mistake to enter the
initial and final values into the
logspace command, instead of
entering the corresponding power of
10
Array Concatenation
Small arrays can be combined together to produce larger
arrays.
However, dimensions must be consistent

Example:
>> x = [1 2 3];
>> y = [x ; 4 5 6]
y=
123
456
>> z = [7 4 2 x]
z=
742123
Mixed calculations between scalars and
arrays

• Matrices can be used in many calculations with scalars


• There is no confusion when we perform addition and subtraction
• Multiplication and division are a little different
• In matrix mathematics the multiplication operator (*) has a very
specific meaning
Summation with a scalar
Addition
between
two arrays
Addition between arrays is
performed on
corresponding elements
Size of arrays should
match
Array Operations
MATRIX Addition (substraction)

 a 11 a 12 a 13   b11 b12 b13 


   
A  a 21 a 22 a 23  M B  b 21 b 22 b 23  M
a a 33  b
 31 a 32  31 b 32 b 33 
N N

 a11 b11 a12 b12 a13 b13 


 
A B  a21 b21 a22 b22 a23 b23  M
 a b a33 b33 
 31 31 a32 b32
N
Matrix Multiplication

Matrix Multiplication is a little bit different

Let A be an (mxn) matrix and B be a (pxq) matrix

For C = A*B to be defined n must be equal to p. (Inner dimensions must match)

Then, the resulting C will be an (m*q) matrix.

n
C ij= ∑ A ik ∗B kj i=1 ,... , m j=1 ,..., q
k =1
Array Operations
• Array multiplication .*
• Array division ./
• Array exponentiation .^

In each case the size of the arrays must match


Array Operations
MATRIX Multiplication (element by element)

 a 11 a 12 a 13   b11 b12 b13 


   
A  a 21 a 22 a 23  M B  b 21 b 22 b 23  M
a a 33  b b 33 
 31 a 32  31 b 32
N N

NOTATION
“dot”
 a11 b11 a12 b12 a13 b13 
 
A B  a21 b21 a22 b22 a23 b23  M
 a b a33 b33 
“multiply”
 31 31 a32 b32
N
Array Operations
Examples: Multiplication & Division (element by element)

 1 2 3  1 2 3
   
A  4 5 6  B  4 5 6 
 7 8 9  7 8 9
   

   
 1 4 9   1 1 1 
   
A B  16 25 36
 A / B  1 1 1 
 49 64 81   
   1 1 1 
   
Example

Newton

Pound
Transpose Operator (‘)
• The transpose operator changes rows to columns or
vice versa.
Transpose Operator (‘)

Help organizing your data


disp()
There are two general forms of the command disp that are
useful in displaying results and annotating them with units or
other information:
1. disp(variable): Displays value of variable without displaying
the variable name.
2. disp(string): Displays string by stripping off the single
quotes and echoing the characters between the quotes.
String: A group of keyboard characters enclosed in single
quote marks (’). The quote marks indicate that the enclosed
characters are to represent ASCII text.
>> temp=78;
>> disp(temp); disp(‘degrees F’)
78
degrees F
Display Options
There are several commands that can be
used to display variables with more control
over the form of the display.
Display Format

• Multiple display formats are available


• No matter what display format you
choose, MATLAB uses double precision
floating point numbers in its calculations
• MATLAB handles both integers and
decimal numbers as floating point
numbers
Default

• The default format is called short


• If an integer is entered it is displayed without trailing
zeros
• If a floating point number is entered four decimal digits
are displayed
Other formats

• Changing the format


affects all subsequent
displays
• format long results in 14
decimal digits
• format bank results in 2
decimal digits
• format short returns the
display to the default 4
decimal digits
Really Big and
Really Small
• When numbers become
too large or too small
for MATLAB to display
using the default format,
it automatically
expresses them in
scientific notation
• You can force scientific
notation with
• format short e
• format long e
Common Scale Factor

• For long and short formats, a common scale factor is


applied to the entire matrix if some of the elements
become very large, or very small. This scale factor is
printed along with the scaled values.
Common Scale
Factor
Saving Your Work
• If you save a MATLAB session performed in the
command window, all that is saved are the values of
the variables you have named
Variables are saved,
not the commands in
the command window
Save either by using the file menu or...

Save with a command in the


command window
Saving your command lines

diary
or
diary on

diary My_diary_file
or
diary (‘My_diary_file’)
LOADING
MATLAB automatically saves
to a .mat file
• If you want to save to another format,
such as .dat, you need to explicitly tell
the program
ASCII format is standard
save <file_name> <variable_list> -ascii between computer
platforms

Again – Remember that the only things being saved are the
values stored in the workspace window – not the commands
from the command window
Script M-Files
• If you want to save your work,
(the commands you entered)
you need to create an M-file
• File->New->M-file
• Type your commands in the edit
window that opens
The Save
and Run Icon
Getting Help
 help – On-line help, display text at command line help, by
itself, lists all help topics
 help topic provides help for the specified topic
 help command provides help for the specified command
 help help provides information on use of the help command
 helpwin – On-line help, separate window for navigation.
 helpdesk – Comprehensive hypertext documentation and
troubleshooting
 help ops: help about operators and special characters
 F1 + topic and help tab from File menu.
lookfor

• You want to do something but you do not know the name of a


function.
• In that case, write the related word you are looking for
• For example:
• >>lookfor square
• It searches and shows all the functions that have the word in their
definition

You might also like