0% found this document useful (0 votes)
7 views

Numerical_Methods_Chap2

Chapter 2 introduces MATLAB, detailing its main characteristics, strengths, and weaknesses as a technical computing environment primarily used for numerical analysis and linear algebra. It covers the basics of starting a MATLAB session, modes of operation, and the use of variables, mathematical functions, and arrays. The chapter also discusses flow control structures, efficient programming techniques, and provides insights into graphics and visualization capabilities within MATLAB.

Uploaded by

obenakum1
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)
7 views

Numerical_Methods_Chap2

Chapter 2 introduces MATLAB, detailing its main characteristics, strengths, and weaknesses as a technical computing environment primarily used for numerical analysis and linear algebra. It covers the basics of starting a MATLAB session, modes of operation, and the use of variables, mathematical functions, and arrays. The chapter also discusses flow control structures, efficient programming techniques, and provides insights into graphics and visualization capabilities within MATLAB.

Uploaded by

obenakum1
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/ 15

Chapter 2: Introduction to MATLAB

Tools and Numerical Methods for Engineering – CEF 352


Second Semester 2022 - 2023

Contents
1 Getting started with MATLAB 3
1.1 Main characteristics of Matlab . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.1.1 What is Matlab? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.1.2 Strengths . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.1.3 Weaknesses . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.2 Opening a Matlab session . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.3 Modes of operation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.3.1 Interactive mode: using Matlab as a calculator . . . . . . . . . . . . . . . . . 4
1.3.2 Creating a script . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
1.4 Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
1.4.1 Naming variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
1.4.2 Special variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
1.4.3 State of a variable . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
1.5 Mathematical functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
1.5.1 Built-in functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
1.5.2 User-defined functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
1.6 Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
1.6.1 What is an array? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
1.6.2 Generating arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
1.6.3 Special arrays and preallocation . . . . . . . . . . . . . . . . . . . . . . . . . 7
1.6.4 Other operations on an array . . . . . . . . . . . . . . . . . . . . . . . . . . 7
1.6.5 Vector and matrix indexing . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
1.7 Flow control structures in Matlab . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
1.7.1 Flow controls possibilities . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
1.7.2 Loop structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
1.8 Efficient programming with Matlab: vectorization . . . . . . . . . . . . . . . . . . . 9
1.8.1 Efficient programming techniques . . . . . . . . . . . . . . . . . . . . . . . . 9
1.8.2 Vectorization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
1.9 Miscellenous . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
1.10 Help . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10

2 Computations with MATLAB 10


2.1 Operations on scalars . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
2.2 Operations on arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
2.2.1 Addition and subtraction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
2.2.2 Multiplication . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
2.2.3 Elementwise operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
2.2.4 Extracting a submatrix . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
2.2.5 Extending a matrix . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
2.2.6 Finding the index of an element . . . . . . . . . . . . . . . . . . . . . . . . . 13
2.2.7 Elements of Linear algebra . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
2.3 Relational and logical operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
2.3.1 Relational operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
2.3.2 Logical operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14

1
3 Graphics and Visualization with MATLAB 14
3.1 2D Plotting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
3.2 Subplots . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
3.3 3D Plotting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14

4 Programming with MATLAB 15

2
1 Getting started with MATLAB
1.1 Main characteristics of Matlab
1.1.1 What is Matlab?
MATLAB was derived from ”Matrix Laboratory”. It is a technical computing environment whose
basic data type is the matrix (or array). That software package was originally designed for solving
numerical analysis and linear algebra type problems using matrices. Matlab is widely used in
engineering since it is well-suited for circuit analysis, signal processing, filter design, optimization,
graphics and animation, data analysis, etc. Matlab can be thought of as an advanced programming
language just like C, Fortran, and Python. MATLAB is more convenient for numerical analysis and
linear algebra.
Note that MATLAB is a registered trademark of MathWorks, Inc.

1.1.2 Strengths
The advantage of working with MATLAB are that:
- MATLAB may behave as a calculator or as a programming language
- MATLAB combine nicely calculation and graphic plotting
- MATLAB is relatively easy to learn
- MATLAB is interpreted (not compiled), errors are easy to fix
- MATLAB is optimized to be relatively fast when performing matrix operations
- MATLAB does have some object-oriented elements

1.1.3 Weaknesses
The issues with working with MATLAB are that:
- MATLAB is not a general purpose programming language such as C, C++, or FORTRAN
- MATLAB is designed for scientific computing, and is not well suitable for other applications
- MATLAB is an interpreted language, slower than a compiled language such as C++
- MATLAB commands are specific for MATLAB usage. Most of them do not have a direct
equivalent with other programming language commands
Note that competitors of Matlab are Python, Scilab, GNU Octave, Rlab, and Mathematica (very
good at symbolic computations).

1.2 Opening a Matlab session


When we start MATLAB, a special window called the MATLAB desktop appears. The desktop is a
window that contains other (sub)windows. The default desktop consists of 4 windows: Workspace,
Command History, Command Window, and Current folder:
• The Command Window: main window, with a prompt >>, where you can type various
commands, short programs or run them
• The Workspace: Displays the variables that are stored in MATLAB environment
• The Current folder window: shows the recent working directory of MATLAB
• The Command History window: stores the commands that have been input using the Com-
mand Window.
The MATLAB window desktop looks like the following:

3
1.3 Modes of operation
Matlab is useful for computing, visualizing and programming. It offers two modes of operation:
An interactive mode when statements are typed in a terminal/prompt (or login shell) and exe-
cuted immediately. In this mode, Matlab can be used as a calculator.
A script/code or batch mode when statements are written to form a code using an editor, then
saved on the disc as a text file or script before being run/executed).

1.3.1 Interactive mode: using Matlab as a calculator


The MATLAB desktop on our computer contains the prompt (>>) in the Command Window. The
prompt symbol does not need to be typed, it appears automatically. As an example of a simple
interactive calculation, we can use the command-line prompt to calculate basic expressions.
Example:
>> 1 + 2*3
ans =
7
ans (short notation for answer) is the default variable used by MATLAB to store the results of
the current calculation. It appears when we run the command for instance by pressing Enter from
the keyboard. The content or value of ans is overwritten at the next calculation. To avoid this,
create a variable for each result.
Example:
>> x = 1 + 2*3

4
x =
7

1.3.2 Creating a script


A script is a collection of commands to be executed in sequence that are written in Matlab editor
and saved as m-file (.m).
To create a script, use one of the following procedures:
- click on the new script button at the top left of Matlab’s screen
- Use the keyboard command crtl+N
- Type edit MyFileName.m from the command line

1.4 Variables
By default, Matlab’s variables are arrays. To create a variable, simply assign a value to a name.

1.4.1 Naming variables


• Variable names must start with a letter and can be followed by letters, digits and underscores.
Numbers can’t be used as variables!
Examples :
x = 2;
greet = ’hello world’;
abc_123 = 0.005;
Counter-example :
1ab = 0.32;
Matlab returns Error: Unexpected MATLAB expression
• Variable names are case sensitive.
Examples :
x = 2; X = 5;
• Variable names can contain up to 63 characters (as of MATLAB 6.5 and newer). Properties of
each variables can be visualized from the workspace.

1.4.2 Special variables


The following names are built-in variables supported by Matlab (don’t use these names for any
other purpose!):
pi Value of π
eps Smallest incremental number (or machine epsilon)
Inf Infinity, e.g. 1/0
NaN Not a number e.g. 0/0
i or j imaginary unit, square root of −1 (preferably use ii or jj for loop counters)
realmin smallest usable positive real number
realmax largest usable positive real number
nargin store the number of input arguments
Note that Matlab may still accept them as variables, but we need not to overwrite their default
values.
Example 1:
>> pi outputs 3.1416.
Example 2:
>> format long
>> pi outputs 3.141592653589793
Example 3:

5
>> pi=2;
>> pi outputs 2.
Example 4:
>> clear restores the default value.

1.4.3 State of a variable


All variables created or modified in a script retain their new value after script execution (but not
for function scripts!).

1.5 Mathematical functions


1.5.1 Built-in functions
• abs - finds absolute value or magnitude of all elements in the matrix
• angle - finds the argument of a complex number
• sign - signum function
• sin, cos, sech. . . - Trignometric functions
• asin, acos. . . - Inverse trignometric functions
• exp - Exponential
• log, log10 - natural logarithm, logarithm (base 10)
• ceil, floor - round towards +infinity, -infinity respectively
• round - round towards nearest integer
• real, imag - real and imaginary part of a complex matrix
• sort - sort elements in ascending order
• sum,prod - summation and product of elements
• max, min - maximum and minimum of arrays
• mean, median – average and median of arrays
• std, var - Standard deviation and variance
etc

1.5.2 User-defined functions


• f= @(x) 1/(x+3); f(2)
• Use function-scripts
Functions look exactly like scripts, but for one difference is that Functions must have a function
declaration:
function[x, y, z] = funName(in1, in2)
No need for return like in Python.
Variable scope: Any variable created within the function but not returned disappears after the
function stops running (They’re called ”local variables”).

Exercise. Write a function with the following declaration:


function PlotSin(f1)
In the function, plot a sine wave with frequency f1, on the interval [0, 2π].
To get good sampling, use 16 points per period.

1.6 Arrays
1.6.1 What is an array?
MATLAB treats all variables as arrays or tables. A matrix can be thought of as an array of order
or size n-by-m where n and m are all greater that one. Vectors are arrays that contain only one

6
row (row vector) OR one column (column vector). Scalars are matrices with only one row AND one
column.

1.6.2 Generating arrays


Scalars :
>> x = 23;
Row vectors :
>> a = [12,10,-3]
>> a = [12 10 -3]
>> b = 1:2:10
>> c = linspace(0,5,10)
Column vectors :
>> u = [12;10;-3]
>> v = [12 10 -3]
Matrices :
>> X = [1,2,3;4,5,6;7,8,9]

1.6.3 Special arrays and preallocation


Preallocation allows us to avoid variables growing inside a loop. Re-allocation of memory is time
consuming. Thus, it is useful to preallocate the required memory by initializing the array to a
default value.
Special arrays are useful in preallocation (automatic initialization) of arrays. There are
• zeros : creates an array of all zeros
>> x1 = zeros(3,4); x2 = zeros(3,1); x3 = zeros(1,4)
• ones : creates an array of all ones
>> y1 = ones(3,4); y2 = ones(3,1); y3 = ones(1,4)
• eye : creates an identity matrix
>> z1 = eye(4);
• Magic square matrix
>> z2 = magic(2);
magic(n) is a matrix constructed from the integers 1 through n2 with equal row and column
sums.
• rand : generates uniformly distributed random numbers in [0,1]
>> w1 = rand(4);
• rand : creates an array of all NaNs (representing uninitialized variables).
>> n=nan(1,69) ;
• linspace : creates a linear vector of values.
>> a=linspace(0,10,5); (Starts at 0, ends at 10 (inclusive),5values)
• diag : Diagonal matrices and diagonal of a matrix. diag(A) returns a column vector of the main
diagonal elements of A.
diag(A,k) returns a column vector of the elements on the k-th diagonal of A.
diag(v) returns a square diagonal matrix with the elements of vector v on the main diagonal.
diag(v,k) places the elements of vector v on the kth diagonal. k=0 represents the main diagonal,
k > 0 is above the main diagonal, and k < 0 is below the main diagonal.

1.6.4 Other operations on an array


• Size of vector
>> a = [12,10,-3]; length(a)
Size of general matrix
>> b = zeros(3,4); size(b)

7
• det : Matrix determinant
• inv : matrix inverse
• eig : evaluates eigenvalues and eigenvectors
• rank : rank of a matrix

1.6.5 Vector and matrix indexing


Vector indexing in MATLAB starts with 1, not 0. So a(n) returns the n-th element. The index
argument can be a vector. In this case, each element is looked up individually, and returned as a
vector of the same size as the index vector.
Example:
>> a = [12,10,-3]; a(2) (outputs 10)
Matrix indexing can be done in two ways: using subscripts (row and column) or using linear indices
(as if the matrix is a vector).
Example:
>> a = [12,10,-3; 7, 5, -2];
>> a(2) (outputs 10)
>> a(4) (outputs 7)
>> a(1,2) (outputs 10)
>> a(2,1) (outputs 7)

1.7 Flow control structures in Matlab


Flow control is a useful way to follow the execution of computer statements.

1.7.1 Flow controls possibilities


• SWITCH statement
Evaluate an expression and choose to execute one of several groups of statements. Each choice
is a case.
Example:
n = input(’Enter a number: ’);
switch n
case -1
disp(’negative one’)
case 0
disp(’zero’)
case 1
disp(’positive one’)
otherwise
disp(’other value’)
end
• BREAK, CONTINUE, RETURN statements
• TRY, CATCH statements
• Loops

1.7.2 Loop structures


• if/else/elseif: Basic flow-control, common to all languages. Syntax:
if cond1
commands1
elseif cond2
commands2

8
else
commands3
end
Too many elseif’s? consider using switch
• for loops: use for a known number of iterations. Syntax:
The loop variable is defined as a vector, is a scalar within the command block, does not have to
have consecutive values (but it’s usually cleaner if they’re consecutive).
The command block is anything between the for line and the end.
• while loop The while loop is like a more general for loop, but is used when we do not need to
know number of iterations.
The command block will execute while the conditional expression is true.
Note: Beware of infinite looping! Use CTRL+C to force-stop the compilation! You can use break
to exit a loop.

1.8 Efficient programming with Matlab: vectorization


1.8.1 Efficient programming techniques
• Avoid using nested loops as far as possible
• In most cases, one can replace nested loops with efficient matrix manipulation.
• Preallocate your arrays when possible
• MATLAB comes with a huge library of in-built functions, use them when necessary
• Avoid using your own functions, MATLAB’s functions are more likely to be efficient than yours.

1.8.2 Vectorization
Vectorization consists in avoiding the use of loops to increase the efficiency of a code in MATLAB. We
can use indexing and matrix operations to avoid loops. For instance, to add every two consecutive
terms.
Example 1: complicated and slow
a=rand(1,100); b=zeros(1,100);
for n=1:100
if n==1
b(n)=a(n);
else b(n)=a(n-1)+a(n);
end
end
Example 2: short and efficient
a=rand(1,100);
b=[0 a(1:end-1)]+a;

1.9 Miscellenous
• Commenting a statement: anything following the sign % is interpreted as a comment.
a %this is a comment
• Redeeming previous computation result (on the terminal):
>> a;
>> ans
Pressing UP direction key from the keyboard also writes ans and importantly, it allows to
browse the previous computations done on the terminal.
• Displaying
Displaying a result or the content of a variable
disp(a)

9
sprintf(a)
a % end the line without semicolon
Displaying a result with a text
disp(’Below is the value of a’)
disp(strcat(’The value of a=’, num2str(a)))
fsprintf(strcat(’The value of a=’, num2str(a)))
Displaying a formatted (boldtype) text
disp(’Hello <strong>World</strong>!’)
fsprintf(’Hello <strong>World</strong>! \n’)

1.10 Help
help is the most useful command to learn Matlab on your own. Where/how to get help? Click
on the help button or on F1 keyboard. Then you can search a function by typing keywords in the
search area of the new window that appears. Equivalent commands in MATLAB’s prompt type
are: help, lookfor, helpwin, helpdesk, demos
Help can also be obtained on the Web at:
http://www.mathworks.com/support
http://www.mathworks.com/products/demos/#
http://www.math.siu.edu/MATLAB/tutorials.html
http://math.ucsd.edu/~driver/21d -s99/MATLAB-primer.html
http://www.mit.edu/~pwb/cssm/
http://www.eecs.umich.edu/~aey/eecs216/.html

Exercise. Make a script with the name HelloWorld.m


By using disp function, allow the script to display the following strings when it runs:
Hello world!
I am going to learn MATLAB!

2 Computations with MATLAB


2.1 Operations on scalars
Arithmetic operations (addition, subtration, division and multiplication) on scalars:
>> a=1.5; b=4.0; c=3.0e-2;
>> a+b
>> a-b
>> b*c
>> a/b
>> b\a
>> (1+1i)*(1+2i)
Exponentiation and compound operations (use parenthesis to enforce the priority) :
>> 4^2
>> (3+4*1j)^2
>> ((2+3)*3)^0.1

2.2 Operations on arrays


2.2.1 Addition and subtraction
Addition and subtraction are carried out elementwise, like for scalars. Added or subtracted matrices
should have the same size, otherwise Matlab will return the error message

10
Matrix dimensions must agree.
Example:
>> a = [12,10,-3]; b = [3,5,6];
>> a+b
>> a-b
Matlab can increment all the elements of a matrix by a single value as follows:
Example:
>> a = [12,10,-3];
>> a+5
ans =
17 15 2

2.2.2 Multiplication
• Scalar multiplication
It is the multiplication of a matrix by a (real) number.
Example:
>> a = [12,10,-3;3,5,6]; b=2*a
• Matrix multiplication
Matrix multiplication in Matlab obeys linear algebra. In computing the product A*B, the number
of columns of matrix A should be the same as the number of rows of matrix B.
Example:
>> a = [12,10,-3;3,5,6]; b=[2;4;8]; a*b

2.2.3 Elementwise operations


• Elementwise multiplication
Multiplication can be carried out elementwise in Matlab using the operator .*. In such a case,
the matrices should have the same size unless one is a scalar, otherwise Matlab will return an error
message.
Example 1:
>> a = [12,10,-3;3,5,6]; b=[2, 4, 8; 3, 5,7]; a.*b
Example 2
>> a = [1,2;1,3]; b = [2,2;2,1];
>> c = a.*b
c =
2 4
2 3
• Element-wise division
>> c = a./b
c =
0.5 1
0.5 3
• Element-wise power operation
>> c = a.^2
c =
1 4
1 9
>> c = a.^ b
c =
1 4
1 3

11
2.2.4 Extracting a submatrix
Unlike C and Python, the index of an element in a Matlab’s array starts at 1 and ends at end.
A portion of a matrix can be extracted and stored in a smaller matrix by specifying the names
of both matrices and the rows and columns to extract.
The syntax for an element is:
a_nm = matrix ( n , m ) ;
Example :
>> X = [1,2,3; 4,5,6; 7,8,9]
>> X_23 = X(2,3)
The syntax for a submatrix is:
sub_matrix = matrix ( r1 : r2 , c1 : c2 ) ;
where r1 and r2 specify the beginning and ending rows and c1 and c2 specify the beginning and
ending columns to be extracted to make the new matrix.
Example :
>> X = [1,2,3;4,5,6;7,8,9]
>> R3 = X(3,1:3)
>> R3 = X(3,:)
>> C2 = X(1:3,2)
>> C2 = X(:,2)
>> A13 = X(3,1:3)
>> A22 = X(1:2 , 2:3)
>> A21 = X(1:2,1)

2.2.5 Extending a matrix


• Extension through a new entry
>> a = [1,2i,0.56]
a =
1 0+2i 0.56
>> a(2,4) = 0.1
a =
1 0+2i 0.56 0
0 0 0 0.1
• Extension through replication of a line or column
>> a = [0,2,4]
a =
0 3 4
>> a(ones(2,1),:) % line replication
0 3 4
0 3 4
>> b = [2;5]
b =
2
5
>> b(:,ones(3,1)) % column replication
2 2 2
5 5 5
• Form a block matrix by concatenation (the dimensions of the new matrix should be consistent).
Example:
>> a = [1,2;3,4]
>> A1 =[a,a]; A2 =[a;a]; A3 =[a,a;a,a]
>> B =[a,2*a;3*a,2*a]

12
Counter-Example:
>> [a,a;a]
• Form a block matrix by replication.
repmat – replicates and tiles a matrix:
>> b = [0,2;3,5]
b =
0 2
3 5
>> b_rep = repmat(b,1,3)
b_rep =
0 2 0 2 0 2
3 5 3 5 3 5

2.2.6 Finding the index of an element


find : searches for the given values in an array/matrix.
To get the minimum value and its index, use min (similar for max):
E.g., vec = [5 3 1 9 7]
[minVal,minInd] = min(vec);
We can find the indices of specific values or ranges
E.g., ind = find(vec == 9); vec(ind) = 8;
ind = find(vec > 2 & vec < 6);
When possible, use logical indexing which is faster than find!
E.g., vec(vec == 9) = 8;

2.2.7 Elements of Linear algebra


• Transpose
a = [1 2 3 4+i]
transpose(a)
a’ (Hermitian transpose if a is complex: transpose and conjugate)
a.’ (vector transpose)
• Sum/product of elements
a = [1 2 3 4+i]
sum(a)
prod(a)
• Determinant (for square matrices only)
a = [1 2 3; 4 -1 5; 8 3 2]; det(a)

2.3 Relational and logical operators


2.3.1 Relational operators
MATLAB supports six relational operators:
Less Than <
Less Than or Equal <=
Greater Than >
Greater Than or Equal >=
Equal To ==
Not Equal To ~= (equivalent to != in C)

13
2.3.2 Logical operators
MATLAB supports three logical operators:
not ~ (highest precedence)
and & (equal precedence with OR)
or | (equal precedence with AND)

3 Graphics and Visualization with MATLAB


MATLAB makes visualizing data fun and easy!

3.1 2D Plotting
The plot function generates dots at each (x, y) pair and then connects thedots with a line. The
vectors x and y must be same size or else an error message will be got.
Example:
x=linspace(0,2*pi,10); (evaluate at 10 points)
y=sin(x);
plot(y); (Plot values of y against their index)
plot(x,y); (Plot y against x)
To make plot of a function look smoother, evaluate at more points.
Explore plot options (color, marker, line style, ...). Look at help plot for a full list of colors,
markers, and line styles.
Exercise:
Open a new figure (use figure). Plot sin(x) and cos(x) over [0, 2π], on the same plot with
different colours.

3.2 Subplots
Subplot function allows to have multiple axes in one figure.
E.g. subplot(2,3,1) makes a figure with 2 rows and 3 columns of axes, and activates the first
axis for plotting. Each axis can have labels, a legend, and a title.
E.g. subplot(2,3,4:6) activates a range of axes and fuses them into one.

3.3 3D Plotting
We can plot in 3 dimensions just as easily as in 2D.
• 3D line plots
Example
time=0:0.001:4*pi; z=time; y=cos(time); x=sin(time);
plot3(x,y,z, ’k’, ’LineWidth’,2); zlabel(’time’)
• Surface plots and contour plots
Use surf, surfc, mesh, meshc, contour, contourf, pcolor...
surf puts vertices at specified points in the space (x,y,z), and connects all the vertices to make
a surface.
Example
x=-pi:0.001:pi; y=-pi:0.001:pi; [X,Y]=meshgrid(x,y); F=cos(X).*sin(Y);
surf(x,y,F)
surf(X,Y,F)
contour(X,Y,F)
NOTE:
We can use tools on figure to rotate it.

14
We can set limits on all 3 axes Use xlim, ylim, zlim.
We can change the colormap.

4 Programming with MATLAB


See examples in next chapters. Topics include:
-Solving a linear system of equations
-Curve fitting with polynomials
-Integration
-Differential equations

References
[1] David Houcque, Introduction to Matlab programming, Lecture notes, Northwestern University,
(version 1.2, August 2005)

15

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy