You are on page 1of 22

CHE F242: Numerical Methods for Chemical Engineers

BITS Pilani
Hyderabad y Campus p

Dr. Vikranth Kumar Surasani

BITS Pilani
Hyderabad Campus

Lecture -3: Introduction to MATLAB Programming

MATLAB
A flagship software which was originally developed as a matrix library. A variety of numerical functions, symbolic computations, and visualization tools have been added to the matrix manipulations. MATLAB is a mathematical and graphical software package; it has numerical, graphical, and programming capabilities. It is a interactive tools. It consists of built-in functions to de many operations, and Toolboxes for specific operations such as, Curve-fitting Curve fitting Partial differential equations Optimization Linear System Analysis Control tool box
CHE F242 Numerical Methods for Chemical Engineers, BITS, Pilani-Hyderabad Campus P-3

Graphical User Interface (GUI)

CHE F242 Numerical Methods for Chemical Engineers, BITS, Pilani-Hyderabad Campus

P-4

Graphical User Interface (GUI)


Command Window

Current Folder Work W k Space S Command History

CHE F242 Numerical Methods for Chemical Engineers, BITS, Pilani-Hyderabad Campus

P-5

Graphical User Interface (GUI)


Command Window
In the Command Window, you should see: >> info will display contact information for the product

demo has demos of several options in MATLAB help will explain any command; help help will explain how help works helpbrowser opens a Help Window

CHE F242 Numerical Methods for Chemical Engineers, BITS, Pilani-Hyderabad Campus

P-6

Variables & Assignments


Variablename = expression e. g.: >> mynum = 6 mynum = 6 >> e. g.: >> 6 = mynum 6 = mynum | Error: The expression to the left of the equals sign is not a valid target for an assignment. assignment Use of semicolon, e.g.: >> res = 9 2; >> Default variable ans >> 6 6+3 3 ans = 9
CHE F242 Numerical Methods for Chemical Engineers, BITS, Pilani-Hyderabad Campus P-7

Variable names
The name must begin with a letter of the alphabet. After that, the name can contain letters, digits, and the underscore character (e.g., value_1), but it cannot have a space. There is a limit to the length of the name; the built-in function namelengthmax tells how many characters this is. MATLAB is case-sensitive. That means that there is a difference between upper- and lowercase letters. So, variables called mynum, MYNUM, and Mynum are all different. different There are certain words called reserved words that cannot be used as variable names. Names of built-in functions can, but should not, be used as variable names. Variable names should always be mnemonics, means they should make some sense to be realistic representation.
CHE F242 Numerical Methods for Chemical Engineers, BITS, Pilani-Hyderabad Campus P-8

Variable information and edits


The following commands relate to variables: who shows variables that have been defined in this Command Window (this just shows the names of the variables) whos shows variables that have been defined in this Command Window (this shows more information on the variables, similar to what is in the Workspace Window) clear clears out all variables so they no longer exist clear variablename clears out a particular variable e. g.: >> clear mynum
CHE F242 Numerical Methods for Chemical Engineers, BITS, Pilani-Hyderabad Campus P-9

The Format Function and Ellipsis


Formatlongdisplaysanyvariableupto 15decimalplaces
>>formatlong >>2*sin(1.4) ans = 1.970899459976920 >>pi ans = 3.141592653589793 Tryformatlooseandcompact >>formatloose >>2^7 ans = 128 >>formatcompact >>2^7 ans = 128 Especiallylongexpressionscanbe continuedonthenextlinebytypingthree ( more) (or )periods, i d which hi his i the h continuation i i operator,ortheellipsis.Forexample, >>3+55 62+4 5 +22 1 ans = 16
CHE F242 Numerical Methods for Chemical Engineers, BITS, Pilani-Hyderabad Campus P-10

Formatlong gdisplays p y any yvariableupto p 15decimalplaces


>>formatshort >>2*sin(1.4) ans = 1.9709 >>pi ans = 3.1416

Operators
Herearesomeofthecommon operatorsthatcanbeusedwith numericexpressions: +addition negation, negation subtraction *multiplication /division(dividedbye.g.10/5is2) \ division(dividedintoe e.g. g 5\10is2) ^exponentiation(e.g.,5^2is25)

OperatorPrecedenceRules () parentheses ^ exponentiation negation *,/,\ allmultiplicationanddivision +, additionandsubtraction

Thinkaboutwhattheresultswould beforthefollowingexpressions, expressions and thentypethemtoverifyyouranswers: >>4^2 1 >>4^(2 1) >>2\3 >>4*2 9/


CHE F242 Numerical Methods for Chemical Engineers, BITS, Pilani-Hyderabad Campus P-11

Built-in Functions
Built-in functions
function(argument) sqrt(x) exp(x) abs(x) log(x) g( ) log10(x) factorial(x)
TRIGONEMETRIC

Rounding functions

Display formats
format short f h : 41.4286 format long: 41.42857142857143 f format t short h t e: 4.1429e+001 4 1429 +001 format long e: 4.142857142857143e+0001 f format t short h t g: 41.429 41 429 format long g: 41.4285714285714 format bank: 41 41.43 43 format compact: eliminates
empty lines

round(x) fix(x) roundtowards zero ceil(x) floor(x)

sin(x) sind(x) cos(x) cosd(x) tan(x) ( ) tand(x) cot(x) cotd(x)

rem(x,y) returns the remainder after xis divided by y (similarto %function inC)

format loose: adds empty p y lines

CHE F242 Numerical Methods for Chemical Engineers, BITS, Pilani-Hyderabad Campus

P-12

Built-in Functions
Try these functions >> abs(4) >> rem(13, ( , 5) ) >> sign(5) ans = 1 >> sign(3) ans = 1

Constants
pi i j inf NaN 3.14159. 1 1 infinity stands for not not a number; number ; e.g., e g the result of 0/0
CHE F242 Numerical Methods for Chemical Engineers, BITS, Pilani-Hyderabad Campus P-13

Types
Integers int8, int16, int32, and int64 >> intmin(int8) ans = 128 >> intmax(int8) ans = 127
Float & Double B d By default, f l numbers b are stored d as the h type double d bl i in MATLAB. MATLAB Th There are, however, h many functions that convert values from one type to another. >> val = 6+3 >> vali = int32(val); ( ); >> whos Name Size Bytes Class Attributes val 1x1 8 double vali li 1 1 1x1 4 i t32 int32

CHE F242 Numerical Methods for Chemical Engineers, BITS, Pilani-Hyderabad Campus

P-14

Random Numbers
How to generate random numbers?
The function rand can be used to generate the real numbers >> rand ans = 0.9501 >> rand ans = 0 2311 0.2311 Rand only generates fractions between 0 and 1. How to generate random numbers between 0 to 10? >> low = 0; >> high = 10; >> rand*(highlow)+low and (high low) low
Randomnumbergeneratorsorfunctions arenottrulyrandom.processstartswith onenumber,calledaseed.Theinitialseed iseitherapredeterminedvalueoritis obtainedfromthebuiltinclockinthe computer.Then,basedonthisseed,a processdeterminesthenextrandom number.Theseareactuallycalledpseudo random;theyarenottrulyrandombecause thereisaprocessthatdeterminesthenext valueeachtime.

How to generate random integers Ho between 0 to 10? >> randi(IMAX,M,N) returns an M-by-N matrix containing pseudorandom integer values drawn from the discrete uniform distribution on 1:IMAX Try randi(100 1:IMAX. randi(100, 10, 10 2)

CHE F242 Numerical Methods for Chemical Engineers, BITS, Pilani-Hyderabad Campus

P-15

Characters and Encoding


Char The type char is used to store either single characters (e.g., x) or strings, which are sequences of characters (e.g., cat). Both characters and strings are enclosed in single quotes. quotes e e. g g.: : >> name = vikranth; Standard ASCII has 128 characters, which have equivalent integer values from 0 to 127. The first 32 (integer values 0 through 31) are nonprinting characters. The letters of the alphabet are in order, which means a comes before b, then c, and so forth forth. >> numequiv = double(a) numequiv = 97 >> numequiv = int32(a) 32( ) >> char(numequiv + 1) >> double(abcd) ans = ans = b 97 98 99 100 >> a + 2 ans = 99 CHE F242 Numerical Methods for Chemical Engineers, BITS, Pilani-Hyderabad Campus

P-16

Vectors and Matrices


Vectors >> v = [1 2 3 4] v= 1 2 3 4 >> v = [1,2,3,4] v= 1 2 3 4 The Colon Operator and Linspace Function >> vec = 1:5 vec = 1 2 3 4 5 >> nv = 1:2:9 nv = 1 3 5 7 9 Si il l the Similarly, th linspace li function f ti creates t a linearly li l spaced vector; linspace(x, y, n) creates a vector with n values in the inclusive range from x to y. >> ls = linspace(3,15,5) linspace(3 15 5) ls = 3 6 9 12 15
CHE F242 Numerical Methods for Chemical Engineers, BITS, Pilani-Hyderabad Campus P-17

Concatenate >> newvec = [nv ls] newvec = 1 3 5 7 9 3 6 9 12 15

Vectors and Matrices


Concatenate >> newvec = [nv ls] newvec = 1 3 5 7 9 3 6 9 12 15 Referring to and Modifying Elements i d index value >> newvec(5) ( ) ans = 9 Use find function >> find(ve==9) ans = 5 8 find function >>b=newvec(4:6) (4 6) b = 7 93 >>newvec([1 ([ 510]) ]) ans = 1 915 >>b(2)=11 b = 7113
P-18

CHE F242 Numerical Methods for Chemical Engineers, BITS, Pilani-Hyderabad Campus

Vectors and Matrices


Creating Column Vectors >> c = [1; 2; 3; 4] c= 1 2 3 4 >> r = 1:3; >> c = r c= 1 2 3 Creating g Matrix Variables >> mat = [4 3 1; 2 5 6] mat = 4 3 1 2 5 6 >> randint([10,30], 2, 4,) ans = 29 22 28 19 14 20 26 10 >> rand(2) ans = 0.2311 0.4860 0.6068 0.8913 >> rand(1,3) ans = 0.7621 0.4565 0.0185 >> ones(3) >> zeros(3) ans = ans = 1 1 0 0 0 1 1 0 0 0 1 1 0 0 0 >> ones (2,4) >> zeros(2,4) ans = ans = 1 1 0 0 0 0 1 1 0 0 0 0

1 1 1 1 1 1 1
P-19

CHE F242 Numerical Methods for Chemical Engineers, BITS, Pilani-Hyderabad Campus

Vectors and Matrices


Referring to and Modifying Matrix Elements >> mat = [2:4; 3:5] mat = 2 3 4 3 4 5 >> mat(2,3) ans = 5 >> mat(1,:) mat(1 :) ans = 2 3 4 >> mat(:, 2) ans = 3 4 >> mat = [2:4; 3:5]; >> mat(1,2) ( ) = 11 mat = 2 11 4 3 4 5 >> mat(2,:) mat(2 :) = 5:7 mat = 2 11 4 5 6 7 >> vec = -2:1 vec = -2 -1 0 1 >> length(vec) ans = 4 >> size(vec) ans = 1 4 >> mat = [1:3; 5:7] mat = 1 5 2 6 3 7 >> size(mat) ans = 3 2 >> length(mat) ans = 3 >> [r c] = size(mat) r= 3 c= 2
P-20

CHE F242 Numerical Methods for Chemical Engineers, BITS, Pilani-Hyderabad Campus

Summary
Common Pitfalls
Following are examples of very common errors: Putting g a space p in a variable name Confusing the format of an assignment statement as expression = variablename rather than variablename = expression The variable name must always be on the left. Using a built-in function name as a variable name, and then trying to use the function Confusing the two division operators / and \ Forgetting the operator precedence rules Confusing the order of arguments passed to functions, for example, to find the remainder of dividing 3 into 10 using rem(3,10) instead of rem(10,3) Not using different types of arguments when testing functions Attempting to create a matrix that does not have the same number of values on each row Forgetting to use parentheses to pass an argument to a function; for example, fix 2.3 instead of fix(2.3). MATLAB returns the ASCII equivalent for each character when h this hi mistake i k is i made. d (What ( h happens h is i that h is i that h it i is i interpreted i d as the function of a string; for example, fix(2.3)).
CHE F242 Numerical Methods for Chemical Engineers, BITS, Pilani-Hyderabad Campus P-21

Summary
Programming Style Guidelines
Do not use names of built-in functions as variable names. If different sets of random numbers are desired, set the seed for the rand function. Do not use just a single index when referring to elements in a matrix; instead, use both the row and column indices. To be general, never assume that the dimensions of any array (vector or matrix) are k known. Instead, d use the h function f i length to determine the number of elements in a vector, and the function size for a matrix, for example: len = length(vec); [r c] = size(mat);

CHE F242 Numerical Methods for Chemical Engineers, BITS, Pilani-Hyderabad Campus

P-22

You might also like