Introduction To Mat Lab: First Year Chemical Engineering Department
Introduction To Mat Lab: First Year Chemical Engineering Department
First Year
Chemical Engineering Department
Fall 2016
PRINCIPLES AND BASIC FEATURES OF MATLAB
In this part we will introduce the basic MATLAB commands and their use. The approach is to
illustrate the use of the commands by examples. Because in this section we will deal with
fundamentals, additional examples of the use of many of these commands will take place as
we proceed throughout the course. Although many examples are provided here, no attempt is
made to cover every possible use or variant of the commands. For additional information on
the individual MATLAB commands, you can refer to the HELP of the MATLAB command
window.
1 Getting Started
1.1 What is MATLAB?
MATLAB is high-performance language for technical computing. It began as a "MATrix
LABoratory" program, intended to provide interactive access to the libraries Linpack and
Eispack. These are carefully tested, high-quality programming packages for solving linear
equations and eigenvalue problems. The basic data element of MATLAB is an array that does
not require dimensioning. This allows the solution of many technical computing problems,
especially those with matrix and vector formulations, in a fraction of the time it would take to
write a program in a scalar non interactive language such as C, FORTRAN or Pascal. More
capabilities have been added as time has passed, many more commands, and very fine
graphics capabilities.
MATLAB integrates computation, visualization, and programming in an easy-to-use
environment where problems and solutions are expressed in a familiar mathematical notation.
Typical uses include:
• Mathematics and computation
• Algorithm development
• Modeling, simulation, and prototyping
• Data analysis, exploration, and visualization
• Scientific and engineering graphics
• Application development, including Graphical User Interface building
In university environments, it is the standard instructional tool for introductory and
advanced courses in mathematics, engineering and science. In industry, MATLAB is the tool
of choice for high productivity research, development and analysis.
>> a = 4/3
a=
1.3333
and assigns to variable a the value of 4 divided by 3. In general, it is a good idea to use
appropriate and memorable names for variables. MATLAB recognizes the first 19 characters
of a variable name and requires only that the first character in a variable name be a letter.
MATLAB is case sensitive, so, for example, a and A are two different variables. All
MATLAB commands are written in lowercase letters.
If you do not care to create a new variable but want to know the value of an expression,
you can type the expression by itself, e.g.,
>> 4/3
which yields
ans =
1.3333
ans =
256
Left division is defined like right division except that the order of dividend and divisor is
swapped, i.e., a\b = (a) -1 b. For a and b scalars, a\b = b/a; in other words, the division is
carried from left to right; for example
>> y = 6\3
returns
y=
0.5000
^ power operator
* multiplication
/ and \ division
+ addition
- subtraction
Precedence of like operators proceeds from left to right, but parentheses can be used to affect
the order of operation. The following three examples illustrate these precedence rules:
>> 1+2^3/4*2
ans =
5
>> 1+2^3/(4*2)
ans =
2
>> (1+2)^3/(4*2)
ans =
3.3750
MATLAB has several predefined variables. These include i and j , both of which denote −1
. Using i or j to generate complex numbers can be very convenient. However, predefined
variables can be overwritten, so be careful using the variable names i and j to mean other than
−1 . For example, many people use i and j as indices for vectors and matrices. As a result,
they often use i or j this way in MATLAB, e.g., by entering i=1 to reassign i to be equal to 1
instead of −1 . It is recommended that you avoid changing the values of the predefined
variables. However, if you choose to do so, it is good practice to reset them after use with the
clear command. For example, to retrieve the predefined value of −1 for i type clear i.
Other predefined variables are
pi, which stands for
Inf, which stands for
NaN, which stands for not a number (e.g. 0/0)
MATLAB will return or NaN when you divide by zero. When this happens, execution of
your calculation will not be terminated; however, MATLAB will warn you of the problem:
>> d = 4/0
warning : Divide by zero
d=
Similarly, MATLAB returns NaN when you attempt to perform certain undefined calculations
e.g.,
>> dd = Inf/Inf
dd =
NaN
Note that in this case no warning is given. In general, you should try to avoid generating Inf
and NaN because they can lead meaningless results in your calculations.
Alexandria University- Faculty of Engineering
Chemical Engineering Department
First Year -Summer 2021
5
3 The MATLAB Workspace and Saving Sessions
When you first start running MATLAB, it is case-sensitive. This means that MATLAB
distinguishes between uppercase and lowercase variable and function names. So, you can
safely have two separate variables named g and G.
MATLAB allows you to clear the command (text) window. The clc command clears the
command window, and give you a fresh >> prompt. The clf command clears the graphics
window and leaves it blank. (we will talk about that later on).If the clear command is followed
by some variables, these variables are erased. If you type
>> clear a b c
only the variables a, b and c will be cleared.
The who command displays the names of all your variables available in the MATLAB
workspace. The whos command gives you the names of all the variables, along with
information about each variable's size, number of elements, number of bytes, density, and
whether the variable is complex..
4 Number Display Format
While all computations in MATLAB are performed in double precision, the format of the
displayed output can be controlled by the following commands:
>> format short fixed point with 4 decimal places (the default)
>> format long fixed point with 14 decimal place
>> format short e scientific notation with 4 decimal places
>> format long e scientific notation with 15 decimal places
>> format bank Fixed format for currency (money).
>> format compact Suppress extra line-feeds.
>> format loose Puts the extra line-feeds back in.
>> format Default. (Same as short).
>> format rat Fraction
When using the help facility, you will find that MATLAB may return more information
than can fit on your command window. To control MATLAB output so that you can view it
page by page, use the more command. Typing more on enables output control. In this case,
MATLAB will display only one page of output.. To see the next line of output hit the return
key. To advance to next page of output hit the space bar. Hitting the “q” key will stop the
outputting and return you to the MATLAB prompt. Type more off to disable paged output.
This controlled output feature is also very useful when you want to view large vectors or
matrices page by page.
The demo command launches an online preview or demo of MATLAB's capabilities.
However, parts of the demo depend on optional additions or toolboxes, not all of these will
have been installed on the system you are using. The demos use both the Figure and
Command windows, you will have to move the Command and Figure windows around
periodically to be able to view the information that is in each of them. In addition, some of the
demos will pause and await a key press in the Command window. If no other method is
available, you can use a CTRL-C to terminate a MATLAB demo or other script. It will
generate a few error messages, but it will get you back to the MATLAB command prompt.
While the demo shows off some of the more powerful features of MATLAB, intro gives
several detailed examples of the basic features and techniques of MATLAB. Intro also makes
greater use of the Command window to display explanations of what it is doing.
Info gives a brief overview of MATLAB and The Mathworks Inc., as well as
information on subscribing to the MATLAB newsletter.
Then typing areacir at the MATLAB prompt will yield the following MATLAB response:
area =
19.6349
circum =
15.7079
which are the area and circumference of a circle of a radius 2.5. Entering help areacir gives
you back the text in the comment lines at the beginning of the file:
% areacir.m: example m-file to
% compute the area and circumference of a circle
It should be obvious that it is very desirable to include at least some brief comment as a header
to each m-file you create.
In a Windows environment you can view the text editor window simultaneously with the
MATLAB command window. This means you can use the two windows to edit a script file
repeatedly and run it in MATLAB without ever quitting MATLAB.
Because MATLAB treats script files exactly as if they are command sequences, all
variables currently in the MATLAB workspace can be used by the script file commands, and
similarly all variables created by the script file are available for use after the script file has
been run. For example after running areacir.m we can examine area as follows:
>> area
area =
19.6349
If you want the function to return more than one value, let's say two values, the first line
of the function definition must start with the word function and can be of the form:
function [variable1 variable2] = f(argument1, argument2,...)
For example suppose we want to create the function called "circle", which returns the area and
the perimeter of a circle with any given radius. The M-file for this function will be:
% This function calculates the area of a circle and its perimeter
% The arguments x, y and p represent the radius, the area and the
% perimeter of the circle, respectively
function [y,p] = f(x)
y = pi*x^2;
p = 2*pi*x;
We can now invoke the function called circle in the same way as we do for commonly used
MATLAB functions. Therefore, in order to find the area of a circle with a radius 6.5, and its
perimeter we can type the following:
[Area Perim]=circle (6.5)
In this case we get
Area =
132.7323
Perim =
40.8407
Text strings can be displayed with the function disp. For example:
disp('this message is hereby displayed')
The blanks command enters a string of blanks, and is used with the disp command;
blanks(n) is a string of n blanks. For example:
disp(['xxx' blanks(20) 'yyy'])
will give
xxx yyy (Notice the 20 blank spaces between xxx and yyy)
In an M-file the user can be prompted to interactively enter input data with the function
input. When, for example, the statement
number = input('Enter the number of students: ')
is encountered, the prompt message is displayed and execution pauses while the user keys in
the input data. Upon pressing the return key, the data is assigned to the variable number and
execution resumes.
8 Vectors and Vector Operations
A vector is a one dimensional array. Let's start off by creating something simple. Enter each
element of the vector (separated by a space) between square brackets, and set it equal to a
variable. For example, to create the vector a, enter into the MATLAB command window:
>> a = [1 2 3 4 5 6 9 8 7]
MATLAB should return:
a=
1 2 3 4 5 6 9 8 7
Let's say you want to create a vector with elements between 0 and 20 evenly spaced in
increments of 2 (this method is frequently used to create a time vector): you can type
>> t = 0:2:20
MATLAB should return:
t=
0 2 4 6 8 10 12 14 16 18 20
Alternatively, the MATLAB function linspace(x1, x2) generates a row vector of 100 linearly
equally spaced points between x1 and x2, while the function linspace(x1, x2, n) generates n
points between x1 and x2. Suppose we want to generate a vector with 10 elements between 18
and 180:
>> linspace(18,180,10)
ans =
18 36 54 72 90 108 126 144 162 180
(Use the MATLAB Help to see what the function LOGSPACE will do !)
Manipulating vectors is almost as easy as creating them. First, suppose you would like to add
2 to each of the elements in vector a. The equation for that looks like:
>> b = a + 2
MATLAB should return:
b=
3 4 5 6 7 8 11 10 9
Subtraction of vectors of the same length works exactly the same way.
MATLAB has a series of functions operating on vectors. Some of these functions are:
max, min, sum, prod, mean, sort.
For example if we type max(v), MATLAB will return 2.3330; typing mean(v), will return -
113.2670, which is the average values of all three elements of the vector v.
MATLAB can also convert a row vector to a column vector. Upon typing:
>> v'
MATLAB will give:
ans =
0.8660
-343.0000
2.3330
9 Polynomials
Polynomials are described in MATLAB by row vectors with elements that are equal to
the polynomial coefficients in order of decreasing powers . For example, to enter the second
degree polynomial p = s2 + 5s + 6 type p = [1 5 6]. The vector p has three elements. Therefore,
MATLAB can interpret a vector of length n+1 as an nth order polynomial. Zero coefficients
must be included to avoid confusion; i.e., q = s3 + 5s + 6 is entered as p = [1 0 5 6]. A
polynomial can be evaluated using the polyval command. For example:
>> polyval (p,1)
ans =
12
gives the value of the polynomial p at s = 1. The roots command is a convenient way to find
the roots of a polynomial, e.g.:
>> r = roots(p)
r =
-3
-2
The commands and functions introduced in this section can change all that. Now we can tell
MATLAB to manipulate expressions that let you compute with mathematical symbols rather
than numbers. This process is often called symbolic math. Here are some examples of
symbolic expressions:
Alexandria University- Faculty of Engineering
Chemical Engineering Department
First Year -Summer 2021
15
d x2
cos(x2) 3x2 + 5x - 1 v= 2x
2
f= dx
dx 1− x
The Symbolic Math Toolbox is a collection of tools (functions) for MATLAB that are used for
manipulating and solving symbolic expressions. There are tools to combine, simplify,
differentiate, integrate and solve algebraic and differential equations. Other tools are used in
liner algebra to derive exact results for inverses, determinants and other properties and
characteristics of symbolic matrices without the error introduced by numerical computations.
1
'1/(2*x^n)'
2x n
1
y= y = '1/sqrt(2*x)'
2x
M = a b M = sym('[a,b;c,d]')
c d
d x2
G=
dx log x
G = diff('x^2/log(x)')
b
x3
f=
a 1− x
dx f = int('x^3/sqrt(1-x)','a','b')
compose can also be used on functions that have different independent variables:
>> compose(h,k,'u','v') % given h(u), k(v), find h(k(v))
ans =
1/(1+sin(v)^2)
The functional inverse of an expression, say f(x), is the expression g(x) that satisfies the
condition g(f(x)) = x. For example, the functional inverse of ex is ln(x), since ln(ex) = x. The
functional inverse of sin(x) is arcsine(x). The finverse function returns the functional inverse
of an expression, and warns you if the result is not unique.
>> finverse('1/x') % inverse of 1/x is 1/x, since '1/(1/x) = x'
ans =
1/x
>> finverse('x^2') %g(x^2) = x has more than one solution
Warning: finverse (x^2) is not unique
ans =
x^(1/2)
>> finverse ('a*x+b') % find the solution to 'g(f(x)) = x'
ans =
-(b-x)/a
>> finverse('a*b+c*d-a*z','a') % find the solution to 'g(f(a)) = a'
ans =
-(c*d-a)/(b-z)
Symbolic expressions can be converted to numeric values and back again. MATLAB has
some very few symbolic functions that can return numeric values. Notice, however, that some
symbolic functions automatically convert a number into its symbolic representation if it is one
of a number of arguments to the function. (Refer to the symop discussed earlier).
ans =
1.6180
The eval function passes a character string to MATLAB to evaluate. Therefore, eval is another
function that can be used to convert a symbolic constant into a number, or to evaluate an
expression:
>> eval(phi) % execute the string '(1+sqrt(5))/2'
ans =
1.6180
We have already worked with polynomials in MATLAB, using vectors whose elements are
the coefficients of the polynomials. The symbolic function sym2poly converts a symbolic
polynomial to its MATLAB equivalent coefficient vector. The function poly2sym does the
reverse, and permits the specification of the variable to use in the resulting expression.
>> f = '2*x^2+x^3-3*x+5' % f is the symbolic polynomial
f=
2*x^2+x^3-3*x+5
>> n=sym2poly(f) %extract the coefficient vector
n=
1 2 -3 5
>> poly2sym(n) %recreate the polynomial in x
ans =
2*x^2+x^3-3*x+5
>> poly2sym(n,'s') %recreate the polynomial in s
ans =
s^3+2*s^2-3*s+5
10.2 SOLVE Symbolic solution of algebraic equations.
SOLVE('eqn1','eqn2',...,'eqnN')
SOLVE('eqn1','eqn2',...,'eqnN','var1,var2,...,varN')
SOLVE('eqn1','eqn2',...,'eqnN','var1','var2',...'varN')
The eqns are symbolic expressions or strings specifying equations. The vars are symbolic
variables or strings specifying the unknown variables. SOLVE seeks zeros of the expressions
or solutions of the equations.
Three different types of output are possible. For one equation and one output, the resulting
solution is returned, with multiple solutions to a nonlinear equation in a symbolic vector. For
several equations and an equal number of outputs, the results are sorted in lexicographic order
and assigned to the outputs. For several equations and a single output, a structure containing
the solutions is returned.
Examples:
ans =
asin(r/p)
x=
[ 1]
[ 3]
y=
[ 1]
[ -3/2]
S=
x: [8x1 sym]
y: [8x1 sym]
[u,v] = solve('a*u^2 + v^2 = 0','u - v = 1') regards 'a' as a parameter and solves the two
equations for u and v.
S = solve('a*u^2 + v^2','u - v = 1','a,u') regards 'v' as a parameter, solves the two
equations, and returns S.a and S.u.
Limitations
X = fzero(inline('abs(x)+1'), 1)
returns NaN since this function does not change sign anywhere on the
real axis (and does not have a zero as well).
X = fzero(@tan,2)
returns X near 1.5708 because the discontinuity of this function near the
point X gives the appearance (numerically) that the function changes sign at X.
To extract the submatrix of A that consists of the second through third rows and of the first
though third columns, use vectors as indices as follows:
>> B = A(2:3,1:3)
B=
3 5 0
0 0 6
The : command as an index by itself indicates that all elements should be selected; i.e.,
A(1,: ) will return the entire first row of matrix A. Typing A( : ) will return all the elements of
A strung out in a column vector.
Matrices can also be manipulated using vectors that contain elements equal to 0 and 1
only. These 0-1 vectors are most frequently generated using relational operators, such as > or
<. If you use a 0-1 vector as a matrix index, rows or columns corresponding to the 1’s are
selected while those corresponding to 0’s are not selected, such as,
>> B = B (:,[0 1 1])
B =
5 0
0 6
MATLAB has commands for generating special matrices. For example, you can create a
diagonal matrix with the diag command using a vector containing the diagonal elements as the
input argument, such as,
>> D = diag([1 2])
D =
1 0
0 2
The MATLAB function ones(n) generates an n-by-n matrix of ones. The function ones(m,n)
or ones([m,n]) generate an m-by-n matrix of ones.
>>ones(3)
ans =
1 1 1
1 1 1
1 1 1
On the other hand, the MATLAB function eye(n), generates an n-by-n identity matrix.
eye(m,n) or eye([m,n]) is an m-by-n matrix with 1's on the diagonal and zeros elsewhere.
>>eye(2)
ans =
1 0
0 1
>> eye(4,3)
ans =
1 0 0
0 1 0
0 0 1
0 0 0
The fliplr command flips the matrix in the left/right direction: fliplr(x) returns x with row
preserved and columns flipped in the left/right direction. For example:
On the other hand the command flipud, flips the matrix in the up/down direction: flipud(x)
returns x with columns preserved and rows flipped in the up/down direction. For example,
x = 1 4 3 6
2 5 becomes 2 5
3 6 1 4
We can also separate any matrix into an upper part and a lower part using triu and tril, which
keep the upper part and the lower part, respectively. For example if:
>>a=
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
if we use the command, triu(a), MATLAB will display:
Closing Notes:
The elements of a matrix being entered are enclosed by brackets
A matrix is entered in "row-major order" [i.e. all of the first row, then all of the second
row, etc];
Rows are separated by a semicolon [or a new line], and the elements of the row may be
separated by either a comma or a space. [Caution: Watch out for extra spaces!]
The element in the ith row and jth column of a is referred to in the usual way:
>> A(2,3) = 10
>> B + D
ans =
6 0
0 8
>> B*D
ans =
5 0
0 12
12 Plotting
12.1 Creating Two-Dimensional Plots
Ordinary two-dimensional plots can be generated in MATLAB using the plot command.
The most basic use of plot is with a single vector as the input argument. Specifically, if you
enter the command plot(v) for any real vector v, MATLAB will create a plot of the elements
of v versus their indices. That is, the first element of v will be plotted versus 1, the second
element of v versus 2, etc.
For v = [1 .35 .15 .05 .01 .005 0 0 0 0]The result is shown if the following figure:
0.9
0.8
0.7
0.6
0.5
0.4
0.3
0.2
0.1
0
0 2 4 6 8 10
examplot.m
% Matrix plotting
% We will create a 5x5 matrix and plot its columns
clf % Clear graphics window
A=[1 2 3 4 5;0.5 0.35 0.29 0.25 0.21;0.35 0.29 0.25 0.21 0.2;…
0.25 0.21 0.2 0.18 0.16]
plot(A) % Plot the matrix
4.5
5.0000
0.2100
0.2000
0.1600
4
Last Column
3.5
4.0000
0.2500
0.2100
0.1800
3 3.0000
0.2900
0.2500
0.2000
2.5 First Column
2
2.0000
0.3500
0.2900
0.2100
1.5
1
0.5000
0.3500
0.2500
1.0000
0.5
0
1 1.5 2 2.5 3 3.5 4
As you can see, the result is hard to understand, primarily because the four individual plots are
not labeled. We will show how to label the line on a plot shortly.
If you enter plot(x,y) where x and y are vectors of the same dimension, MATLAB will
plot y versus x. Running the script file genplot.m will generate such a plot:
40
35
30
25
20
15
10
0
3 4 5 6 7 8 9 10
-3
x 10
The first line generates values of temperatures from 100 to 300°C in increments of 50°C. After
assigning values for the constants of the equation the corresponding rate constant values are
computed. Notice here the use of the . between the operators: e.g. K0.exp(-E./(1.987.*T)). If
we had used K0*exp(-E/(1.987*T)), we would have gotten an error message for trying to
multiply two matrices of incompatible dimensions. In general, the collection of array operation
commands (.* , .^ , ./ , etc.) is very useful in plotting. We generate the vectors x and y by
letting x be the reciprocal of the temperature and y be the rate constant. The generated plot
shows the relationship between the rate constant and the reciprocal of the temperature. Note
that the first argument of the plot command is interpreted as the horizontal axis and the second
argument as the vertical axis.
Once you have generated a plot, you can read data off the plot by using the command
ginput. For example, you can use ginput to find the coordinates of the data points of the
generated figure. Entering [xpoint,ypoint] = ginput will put a crosshair on the graph. You can
move the crosshair with the mouse. When you have moved the crosshair to a point of interest,
depress the mouse button, and MATLAB will compute the coordinates at the crosshair. You
can extract coordinates for many different points at a time by successively repeating this
procedure. When you are done, hit the enter or return key. You may need to be sure that the
Helpful Hints
We will now see some ways of customizing plots such as adding new information like
titles and labels to a graph for better display of data.
The title, xlabel and ylabel commands title and label the axes of your plot. For example
add the following lines to the end of the file genplot.m
title('Plot of an Arrhenius-type relation')
xlabel('Reciprocal of temperature, 1/T')
ylabel('Value of K')
grid
returns the following plot:
35
30
25
20
15
10
0
3 4 5 6 7 8 9 10
Reciprocal of temperature, 1/T -3
x 10
Labeling of arbitrary points on a graph can be done with the text or the gtext commands. The
text command performs manual labeling: i.e. you must specify the coordinates on the graph
for the position of the first letter of label. The gtext command provides interactive labeling:
i.e. after generating your plot enter gtext('label'). MATLAB will provide a crosshair in the
graphics window which you can move to the desired label position using the mouse. When
Next, try replacing the command plot(x,y) in genplot.m with plot(x,y,'..') and rerun it.
Instead of the default solid-line plot, you should see a dotted-line plot. MATLAB provides a
variety of line and point types and colors that you can use to make your plots look exactly as
you wish. They are particularly useful when you need to distinguish between different lines on
a multiple-line plot and you do not like the default line appearance. You can specify your own
colors, line styles and markers. This is particularly useful if you have more that a data set to be
presented on the same graph. The following table shows the symbols used for these options:
Suppose, for example you have the following two sets of data, which represent the variation of
the corrosion rate of zinc with Reynolds number, in solutions of different concentrations:
First we create two sets of vectors: one for the 1% salt, and one for the 3.5% salt:
>> Re1=[392.312 977.412 1948.1 2952.46 4018.06]; Rate1=[524.35 525.6 566.42
702.84 775.75]
>> Re2=[396.709 991.773 1983.55 2895.45 3847.39]; Rate2=[660.22 689.27 889.57 905.68
1024.98]
The first relation drawn is Re1 vs. Rate1, with red asterisk and yellow solid line (bottom line); the
second relation is Re2 vs. Rates with green circles and magenta solid line (top line)
The plot can, of course be customized to have a title and labeled axes as explained earlier.
Furthermore, one graphics window can hold more than one set of axes. The current figure can be
subdivided into many plotting areas: the command subplot(m,n,p) subdivides the current figure
window into an m-by-n matrix of plotting areas and chooses the pth area to be active. The subplots
are numbered left to right along the top row, then the second row, etc…
For example:
>> subplot (1,2,1) %pick the upper left of a 1 by 2 grid of subplots
>> plot (Re1, Rate1), title('Corrosion rate for a 1% salt concentration')
>> subplot (1,2,2) %pick the upper right of a 1 by 2 grid of subplots
>> plot (Re2, Rate2), title('Corrosion rate for a 3.5% salt concentration')
MATLAB defines a mesh surface by the Z-coordinates of points above a rectangular grid in the
x-y plane. It forms the mesh plot by joining adjacent points with straight lines. The results looks
like a fishing net with knots at the data points. For example, consider the peaks function:
>> [x,y,z]=peaks(30);
>> mesh(x,y,z)
>> [x,y,z]=peaks(30);
>> surf(x,y,z)
>> xlabel('X-Axis'), ylabel('Y-Axis'), zlabel('Z-Axis')
Now the region of interest shows up a little better, but there is still part of plot below the
ground. The plot could be fixed by changing the time range and reissuing the ezplot
command, e.g. ezplot(y,[0 5.1623]). Once the plot is in he figure window, it can be modified
like any other plot. Let's scale both axes of the current plot and add a title a labels:
The columns of the expression are stored one at a time in the variable and then the
following statements, up to the END, are executed. The expression is often of the form X:Y,
in which case its columns are simply scalars. Some examples (assume N has already been
assigned a value).
FOR I = 1:N,
FOR J = 1:N,
A(I,J) = 1/(I+J-1);
END
END
Long loops are more memory efficient when the colon expression appears in the FOR
statement since the index vector is never created.
12.6 Break
The BREAK statement can be used to terminate the loop prematurely. BREAK Terminate
execution of WHILE or FOR loop. BREAK terminates the execution of FOR and WHILE
loops. In nested loops, BREAK exits from the innermost loop only.
BREAK is not defined outside of a FOR or WHILE loop. Use RETURN in this context
instead.
12.7. Continue
CONTINUE Pass control to the next iteration of FOR or WHILE loop.
CONTINUE passes control to the next iteration of FOR or WHILE loop
in which it appears, skipping any remaining statements in the body
of the FOR or WHILE loop.
In nested loops, CONTINUE passes control to the next iteration of FOR or WHILE loop
enclosing it.
IF expression
statements
ELSEIF expression
statements
ELSE
statements
END
The statements are executed if the real part of the expression has all non-zero elements. The
ELSE and ELSEIF parts are optional. Zero or more ELSEIF parts can be used as well as
nested IF's. The expression is usually of the form expr rop expr where rop is ==, <, >, <=, >=,
or ~=.
Example
if I == J
A(I,J) = 2;
elseif abs(I-J) == 1
A(I,J) = -1;
else
A(I,J) = 0;
end
12.2. Else
ELSE Used with IF.
ELSE is used with IF. The statements after the ELSE are executed
if all the preceding IF and ELSEIF expressions are false.
12.4. While
WHILE Repeat statements an indefinite number of times.
The general form of a WHILE statement is:
WHILE expression
statements
END
The statements are executed while the real part of the expression has all non-zero elements.
The expression is usually the result of expr rop expr where rop is ==, <, >, <=, >=, or ~=.
E = 0*A; F = E + eye(size(E)); N = 1;
while norm(E+F-E,1) > 0,
E = E + F;
F = A*F/N;
N = N + 1;
end
13. Interpolation
13.1 One Dimensional Interpolation
INTERP1 1-D interpolation (table lookup).
YI = INTERP1(X,Y,XI) interpolates to find YI, the values of the underlying function Y at
the points in the vector XI. The vector X specifies the points at which the data Y is given. If Y
is a matrix, then the interpolation is performed for each column of Y and YI will be
length(XI)-by-size(Y,2).
XI can be a row vector, in which case it specifies a matrix with constant columns. Similarly,
YI can be a column vector and it specifies a matrix with constant rows.
All the interpolation methods require that X and Y be monotonic and plaid (as if they were
created using MESHGRID). If you provide two monotonic vectors, interp2 changes them to a
plaid internally.
X and Y can be non-uniformly spaced.
For example, to generate a coarse approximation of PEAKS and interpolate over a finer
mesh:
[x,y,z] = peaks(10); [xi,yi] = meshgrid(-3:.1:3,-3:.1:3);
zi = interp2(x,y,z,xi,yi); mesh(xi,yi,zi)