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

Interactive computing with MATLAB

The document provides an introduction to using Matlab for interactive computing, detailing how to start Matlab, use the command window, and perform basic calculations. It covers variable creation, built-in functions, and methods for obtaining help within the software. Additionally, it explains matrix and vector operations, including creation and manipulation of these data structures.

Uploaded by

Williams Ademola
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Interactive computing with MATLAB

The document provides an introduction to using Matlab for interactive computing, detailing how to start Matlab, use the command window, and perform basic calculations. It covers variable creation, built-in functions, and methods for obtaining help within the software. Additionally, it explains matrix and vector operations, including creation and manipulation of these data structures.

Uploaded by

Williams Ademola
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 65

Interactive Computing

with Matlab
Gerald W. Recktenwald
Department of Mechanical Engineering
Portland State University
[email protected]
Starting Matlab

• Double click on the Matlab icon, or on unix systems type “matlab”


at the command line.
• After startup Matlab displays a command window that is used to
enter commands and display text-only results.
• Enter Commands at the command prompt:
>> for full version
EDU> for educational version
• Matlab responds to commands by printing text in the command
window, or by opening a figure window for graphical output.
• Toggle between windows by clicking on them with the mouse.

NMM: Interactive Computing with Matlab page 4


Matlab Desktop
Command Prompt: Recent Directory Menu:
Enter typed commands here. Used to change current
Text results are displayed here. working directory.

Launch Pad/Workspace:
Used to browse documentation,
or view values of variables in
the workspace

Select Launch Pad tab or


Workspace tab

Command History/Current
Directory: View and re-enter
previously typed commands,
or change directories

Select Command History tab


or Current Directory tab

NMM: Interactive Computing with Matlab page 5


Matlab as a Calculator (1)

Enter formulas at the command prompt


>> 2 + 6 - 4 (press return after ‘‘4’’)
ans =
4

>> ans/2
ans =
2

NMM: Interactive Computing with Matlab page 7


Matlab as a Calculator (2)

Define and use variables


>> a = 5
a =
5

>> b = 6
b =
6

>> c = b/a
c =
1.2000

NMM: Interactive Computing with Matlab page 8


Built-in Variables

pi (= π) and ans are a built-in variables


>> pi
ans =
3.1416

>> sin(ans/4)
ans =
0.7071

Note: There is no “degrees” mode. All angles are measured in radians.

NMM: Interactive Computing with Matlab page 9


Built-in Functions

Many standard mathematical functions, such as sin, cos, log, and


log10, are built-in
>> log(256) log(x) computes the natural logarithm of x
ans =
5.5452

>> log10(256) log10(x) is the base 10 logarithm


ans =
2.4082

>> log2(256) log2(x) is the base 2 logarithm


ans =
8

NMM: Interactive Computing with Matlab page 10


Ways to Get Help

• Use on-line help to request info on a specific function


>> help sqrt

• In Matlab version 6 and later the doc function opens the on-line
version of the manual. This is very helpful for more complex commands.
>> doc plot

• Use lookfor to find functions by keywords


>> lookfor functionName

NMM: Interactive Computing with Matlab page 11


On-line Help (1)

Syntax:
help functionName

Example:
>> help log

produces
LOG Natural logarithm.
LOG(X) is the natural logarithm of the elements of X.
Complex results are produced if X is not positive.

See also LOG2, LOG10, EXP, LOGM.

The help function provides a compact summary of how to use a


command. Use the doc function to get more in-depth information.

NMM: Interactive Computing with Matlab page 12


On-line Help (2)

The help browser opens when you type a doc command:


>> doc plot

NMM: Interactive Computing with Matlab page 13


Looking for Functions

Syntax:
lookfor string

searches first line of function descriptions for “string”.


Example:
>> lookfor cosine

produces
ACOS Inverse cosine.
ACOSH Inverse hyperbolic cosine.
COS Cosine.
COSH Hyperbolic cosine.

NMM: Interactive Computing with Matlab page 14


Strategies for Interactive Computing

• Use the command window for short sequences of calculations


• Later we’ll learn how to build reusable functions for more complex tasks.
• The command window is good for testing ideas and running sequences
of operations contained in functions
• Any command executed in the command window can also be used in a
function.

Let’s continue with a tour of interactive computing.

NMM: Interactive Computing with Matlab page 15


Suppress Output with Semicolon (1)

Results of intermediate steps can be suppressed with semicolons.


Example: Assign values to x, y, and z, but only display the value of z in
the command window:
>> x = 5;
>> y = sqrt(59);
>> z = log(y) + x^0.25
z =
3.5341

NMM: Interactive Computing with Matlab page 16


Suppress Output with Semicolon (2)

Type variable name and omit the semicolon to print the value of a variable
(that is already defined)
>> x = 5;
>> y = sqrt(59);
>> z = log(y) + x^0.25
z =
3.5341
>> y
y =
7.6811 ( = log(sqrt(59)) + 5^0.25 )

NMM: Interactive Computing with Matlab page 17


Multiple Statements per Line

Use commas or semicolons to enter more than one statement at once.


Commas allow multiple statements per line without suppressing output.

>> a = 5; b = sin(a), c = cosh(a)


b =
-0.9589

c =
74.2099

NMM: Interactive Computing with Matlab page 18


Matlab Variables Names
Legal variable names:
• Begin with one of a–z or A–Z
• Have remaining characters chosen from a–z, A–Z, 0–9, or
• Have a maximum length of 31 characters
• Should not be the name of a built-in variable, built-in function, or
user-defined function

Examples: Note: mySum and mysum are different


xxxxxxxxx variables. Matlab is case
pipeRadius sensitive.
widgets_per_box
mySum
mysum

NMM: Interactive Computing with Matlab page 19


Built-in Matlab Variables (1)

Name Meaning
ans value of an expression when that expression is not assigned to
a variable
eps floating point precision
pi π, (3.141492 . . .)
realmax largest positive floating point number
realmin smallest positive floating point number
Inf ∞, a number larger than realmax,
the result of evaluating 1/0.
NaN not a number, the result of evaluating 0/0

NMM: Interactive Computing with Matlab page 20


Built-in Matlab Variables (2)

Rule: Only use built-in variables on the right hand side of an expression.
Reassigning the value of a built-in variable can create problems
with built-in functions.


Exception: i and j are preassigned to −1. One or both of i or j are
often reassigned as loop indices. More on this later.

NMM: Interactive Computing with Matlab page 21


Matrices and Vectors
All Matlab variables are matrices
• A vector is a matrix with one row or one column.
• A scalar is a matrix with one row and one column.
• A character string is a row of column vector of characters.

Consequences:
• Rules of linear algebra apply to addition, subtraction and multiplication.
• Elements in the vectors and matrices are addressed with Fortran-like
subscript notation, e.g.,, x(2), A(4,5). Usually this notation is clear
from context, but it can be confused with a function call,
y = sqrt(5) sqrt is a built-in function
z = f(3) Is f a function or variable?

NMM: Interactive Computing with Matlab page 22


Creating Matlab Variables

Matlab variables are created with an assignment statement


>> x = expression

where expression is a legal combinations of numerical values,


mathematical operators, variables, and function calls.
The expression can involve:
• Manual entry
• Built-in functions that return matrices
• Custom (user-written) functions that return matrices
• Loading matrices from text files or “mat” files

NMM: Interactive Computing with Matlab page 23


Element-by-Element Creation of Matrices and Vectors (1)

A matrix, a column vector, As Matlab variables:


and a row vector: >> A = [3 2; 3 1; 1 4]
A =
 
3 2 3 2
A = 3 1 3 1
1 4
1 4
>> x = [5; 7; 9; 2]
  x =
5 5
7 7
x=
9

9
2 2
>> v = [9 -3 4 1]
 
v = 9 −3 4 1 v =
9 -3 4 1

NMM: Interactive Computing with Matlab page 24


Element-by-Element Creation of Matrices and Vectors (2)

For manual entry, the elements in a vector are enclosed in square brackets.
When creating a row vector, separate elements with a space.
>> v = [7 3 9]
v =
7 3 9

Separate columns with a semicolon


>> w = [2; 6; 1]
w =
2
6
1

NMM: Interactive Computing with Matlab page 25


Element-by-Element Creation of Matrices and Vectors (3)

When assigning elements to matrix, row elements are separated by spaces,


and columns are separated by semicolons
>> A = [1 2 3; 5 7 11; 13 17 19]
A =
1 2 3
5 7 11
13 17 19

NMM: Interactive Computing with Matlab page 26


Transpose Operator (1)

Once it is created, a variable can be transformed with other operators.


The transpose operator converts a row vector to a column vector (and vice
versa), and it changes the rows of a matrix to columns.
>> v = [2 4 1 7]
v =
2 4 1 7

>> w = v’
w =
2
4
1
7

NMM: Interactive Computing with Matlab page 27


Transpose Operator (2)

>> A = [1 2 3; 4 5 6; 7 8 9 ]
A =
1 2 3
4 5 6
7 8 9

>> B = A’
B =
1 4 7
2 5 8
3 6 9

NMM: Interactive Computing with Matlab page 28


Overwriting Variables
Once a variable has been created, it can be reassigned
>> x = 2;
>> x = x + 2
x =
4

>> y = [1 2 3 4]
y =
1 2 3 4

>> y = y’
y =
1
2
3
4

NMM: Interactive Computing with Matlab page 29


Using Functions to Create Matrices and Vectors

Create vectors with built-in functions:

linspace and logspace

Create matrices with built-in functions:

ones, zeros, eye, diag, . . .

Note that ones and zeros can also be used to create vectors.

NMM: Interactive Computing with Matlab page 30


Creating vectors with linspace (1)

The linspace function creates vectors with elements having uniform


linear spacing.
Syntax:
x = linspace(startValue,endValue)
x = linspace(startValue,endValue,nelements)

Examples:
>> u = linspace(0.0,0.25,5)
u =
0 0.0625 0.1250 0.1875 0.2500

>> u = linspace(0.0,0.25);

Remember: Ending a statement with semicolon suppresses the output.

NMM: Interactive Computing with Matlab page 31


Creating vectors with linspace (2)

Column vectors are created by appending the transpose operator to


linspace
>> v = linspace(0,9,4)’
v =
0
3
6
9

NMM: Interactive Computing with Matlab page 32


Example: A Table of Trig Functions
>> x = linspace(0,2*pi,6)’; (note transpose)
>> y = sin(x);
>> z = cos(x);
>> [x y z]
ans =
0 0 1.0000
1.2566 0.9511 0.3090
2.5133 0.5878 -0.8090
3.7699 -0.5878 -0.8090
5.0265 -0.9511 0.3090
6.2832 0 1.0000

The expressions y = sin(x) and z = cos(x) take advantage of


vectorization. If the input to a vectorized function is a vector or matrix,
the output is often a vector or matrix having the same shape. More on this
later.

NMM: Interactive Computing with Matlab page 33


Functions to Create Matrices (2)

Use ones and zeros to set intial values of a matrix or vector.


Syntax:
A = ones(nrows,ncols)
A = zeros(nrows,ncols)

Examples:
>> D = ones(3,3)
D =
1 1 1
1 1 1
1 1 1
>> E = ones(2,4)
E =
1 1 1 1
1 1 1 1

NMM: Interactive Computing with Matlab page 36


Functions to Create Matrices (3)

ones and zeros are also used to create vectors. To do so, set either
nrows or ncols to 1.
>> s = ones(1,4)
s =
1 1 1 1

>> t = zeros(3,1)
t =
0
0
0

NMM: Interactive Computing with Matlab page 37


Functions to Create Matrices (4)

The eye function creates identity matrices of a specified size. It can also
create non-square matrices with ones on the main diagonal.
Syntax:
A = eye(n)
A = eye(nrows,ncols)

Examples:
>> C = eye(5)
C =
1 0 0 0 0
0 1 0 0 0
0 0 1 0 0
0 0 0 1 0
0 0 0 0 1

NMM: Interactive Computing with Matlab page 38


Functions to Create Matrices (5)

The optional second input argument to eye allows non-square matrices to


be created.
>> D = eye(3,5)
D =
1 0 0 0 0
0 1 0 0 0
0 0 1 0 0

where Di,j = 1 whenever i = j.

NMM: Interactive Computing with Matlab page 39


Functions to Create Matrices (6)

The diag function can either create a matrix with specified diagonal
elements, or extract the diagonal elements from a matrix
Syntax:
A = diag(v)
v = diag(A)

Example: Use diag to create a matrix


>> v = [1 2 3];
>> A = diag(v)
A =
1 0 0
0 2 0
0 0 3

NMM: Interactive Computing with Matlab page 40


Functions to Create Matrices (7)

Example: Use diag to extract the diagonal of a matrix


>> B = [1:4; 5:8; 9:12]
B =
1 2 3 4
5 6 7 8
9 10 11 12

>> w = diag(B)
w =
1
6
11

NMM: Interactive Computing with Matlab page 41


Functions to Create Matrices (8)

The action of the diag function depends on the characteristics and


number of the input(s). This polymorphic behavior of Matlab functions
is common. Refer to the on-line documentation for the possible variations.
>> A = diag([3 2 1]) Create a matrix with a specified diagonal
A =
3 0 0
0 2 0
0 0 1

>> B = [4 2 2; 3 6 9; 1 1 7];
>> v = diag(B) Extract the diagonal of a matrix
v =
4
6
7

NMM: Interactive Computing with Matlab page 42


Subscript Notation (1)

If A is a matrix, A(i,j) selects the element in the ith row and jth column.
Subscript notation can be used on the right hand side of an expression to
refer to a matrix element.
>> A = [1 2 3; 4 5 6; 7 8 9];
>> b = A(3,2)
b =
8

>> c = A(1,1)
c =
1

NMM: Interactive Computing with Matlab page 43


Subscript Notation (1)

Subscript notation is also used to assign matrix elements


>> A(1,1) = c/b
A =
0.2500 2.0000 3.0000
4.0000 5.0000 6.0000
7.0000 8.0000 9.0000

Referring to elements beyond the dimensions the matrix results in an error


>> A = [1 2 3; 4 5 6; 7 8 9];
>> A(1,4)
??? Index exceeds matrix dimensions.

NMM: Interactive Computing with Matlab page 44


Subscript Notation (1)
Assigning an element that is beyond the existing dimensions of the matrix
causes the matrix to be resized!
>> A = [1 2 3; 4 5 6; 7 8 9];
A =
1 2 3
4 5 6
7 8 9

>> A(4,4) = 11
A =
1 2 3 0
4 5 6 0
7 8 9 0
0 0 0 11

In other words, Matlab automatically resizes matrices on the fly.

NMM: Interactive Computing with Matlab page 45


Colon Notation (1)

Colon notation is very powerful and very important in the effective use of
Matlab. The colon is used as both an operator and as a wildcard.

Use colon notation to:


• create vectors
• refer to or extract ranges of matrix elements

NMM: Interactive Computing with Matlab page 46


Colon Notation (2)

Syntax:
startValue:endValue
startValue:increment:endValue

Note: startValue, increment, and endValue do not need to be


integers

NMM: Interactive Computing with Matlab page 47


Colon Notation (3)

Creating row vectors:


>> s = 1:4
s =
1 2 3 4

>> t = 0:0.1:0.4
t =
0 0.1000 0.2000 0.3000 0.4000

NMM: Interactive Computing with Matlab page 48


Colon Notation (4)

Creating column vectors:


>> u = (1:5)’
u =
1
2
3
4
5

>> v = 1:5’
v =
1 2 3 4 5

v is a row vector because 1:5’ creates a vector between 1 and the


transpose of 5.

NMM: Interactive Computing with Matlab page 49


Colon Notation (5)

Use colon as a wildcard to refer to an entire column or row


>> A = [1 2 3; 4 5 6; 7 8 9];
>> A(:,1)
ans =
1
4
7

>> A(2,:)
ans =
4 5 6

NMM: Interactive Computing with Matlab page 50


Colon Notation (6)

Or use colon notation to refer to subsets of columns or rows


>> A(2:3,1)
ans =
4
7

>> A(1:2,2:3)
ans =
ans =
2 3
5 6

NMM: Interactive Computing with Matlab page 51


Colon Notation (7)

Colon notation is often used in compact expressions to obtain results that


would otherwise require several steps.
Example:
>> A = ones(8,8);
>> A(3:6,3:6) = zeros(4,4)
A =
1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1
1 1 0 0 0 0 1 1
1 1 0 0 0 0 1 1
1 1 0 0 0 0 1 1
1 1 0 0 0 0 1 1
1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1

NMM: Interactive Computing with Matlab page 52


Colon Notation (8)

Finally, colon notation is used to convert any vector or matrix to a column


vector.
Example:
>> x = 1:4;
>> y = x(:)
y =
1
2
3
4

NMM: Interactive Computing with Matlab page 53


Colon Notation (9)

Colon notation converts a matrix to a column vector by appending the


columns of the input matrix
>> A = rand(2,3);
>> v = A(:)
v =
0.9501
0.2311
0.6068
0.4860
0.8913
0.7621
0.4565

Note: The rand function generates random elements between zero and one.
Repeating the preceding statements will, in all likelihood, produce different
numerical values for the elements of v.

NMM: Interactive Computing with Matlab page 54


Array Operators

Array operators support element-by-element operations that are not


defined by the rules of linear algebra.
Array operators have a period prepended to a standard operator.

Symbol Operation
.* element-by-element multiplication
./ element-by-element “right” division
.\ element-by-element “left” division
.^ element-by-element exponentiation
Array operators are a very important tool for writing vectorized code.

NMM: Interactive Computing with Matlab page 78


Using Array Operators (1)

Examples: Element-by-element multiplication and division


>> u = [1 2 3];
>> v = [4 5 6];

Use .* and ./ for element-by-element multiplication and division


>> w = u.*v
w =
4 10 18

>> x = u./v
x =
0.2500 0.4000 0.5000

NMM: Interactive Computing with Matlab page 79


Using Array Operators (1)

Examples: Element-by-element multiplication and division


>> u = [1 2 3];
>> v = [4 5 6];
>> y = sin(pi*u/2) .* cos(pi*v/2)
y =
1 0 1

>> z = sin(pi*u/2) ./ cos(pi*v/2)

Warning: Divide by zero.


z =
1 NaN 1

NMM: Interactive Computing with Matlab page 80


Using Array Operators (2)

Examples: Application to matrices


>> A = [1 2 3 4; 5 6 7 8];
>> B = [8 7 6 5; 4 3 2 1];
>> A.*B
ans =
8 14 18 20
20 18 14 8

>> A*B
??? Error using ==> *
Inner matrix dimensions must agree.

The last statement causes an error because the number of columns in A is


not equal to the number of rows in B — a requirement for A and B to be
compatible for matrix multiplication.

NMM: Interactive Computing with Matlab page 81


Using Array Operators (3)

>> A = [1 2 3 4; 5 6 7 8];
>> B = [8 7 6 5; 4 3 2 1];
>> A*B’
ans =
60 20
164 60

The number of columns in A is equal to the number of rows in BT , so A*B’


is a legal matrix-matrix multiplication.
Array operators also apply to matrix powers.
>> A.^2
ans =
1 4 9 16
25 36 49 64

NMM: Interactive Computing with Matlab page 82


Plotting

• Plotting (x, y) data

• Axis scaling and annotation

• 2D (contour) and 3D (surface) plotting

NMM: Interactive Computing with Matlab page 90


Plotting (x, y) Data (1)

Two dimensional plots are created with the plot function


Syntax:
plot(x,y)
plot(xdata,ydata,symbol)
plot(x1,y1,x2,y2,...)
plot(x1,y1,symbol1,x2,y2,symbol2,...)

Note: x and y must have the same shape, x1 and y1 must have the
same shape, x2 and y2 must have the same shape, etc.

NMM: Interactive Computing with Matlab page 91


Plotting (x, y) Data (2)

1
Example: A simple line plot 0.8

>> x = linspace(0,2*pi); 0.6

>> y = sin(x); 0.4

>> plot(x,y); 0.2

−0.2

−0.4

−0.6

−0.8

−1
0 1 2 3 4 5 6 7

NMM: Interactive Computing with Matlab page 92


Line and Symbol Types (1)

The curves for a data set are drawn from combinations of the color,
symbol, and line types in the following table.
Color Symbols Line
y yellow . point ^ triangle (up) - solid
m magenta o circle < triangle (left) : dotted
c cyan x x-mark > triangle (right) -. dashdot
r red + plus p pentagram -- dashed
g green * star h hexagram
b blue s square
w white d diamond
k black v triangle
(down)

To choose a color/symbol/line style, chose one entry from each column.

NMM: Interactive Computing with Matlab page 93


Line and Symbol Types (2)

Examples:
Put yellow circles at the data points:
plot(x,y,’yo’)

Plot a red dashed line with no symbols:


plot(x,y,’r--’)

Put black diamonds at each data point and connect the diamonds with
black dashed lines:
plot(x,y,’kd--’)

NMM: Interactive Computing with Matlab page 94


Alternative Axis Scaling (1)

Combinations of linear and logarithmic scaling are obtained with functions


that, other than their name, have the same syntax as the plot function.
Name Axis scaling
loglog log10(y) versus log10(x)
plot linear y versus x
semilogx linear y versus log10(x)
semilogy log10(y) versus linear x

Note: As expected, use of logarithmic axis scaling for data sets with
negative or zero values results in a error. Matlab will complain
and then plot only the positive (nonzero) data.

NMM: Interactive Computing with Matlab page 95


Alternative Axis Scaling (2)

10
Example:
8
>> x = linspace(0,3);
6
>> y = 10*exp(-2*x);
>> plot(x,y); 4

0
0 1 2 3
1
10
>> semilogy(x,y);
0
10

-1
10

-2
10
0 1 2 3

NMM: Interactive Computing with Matlab page 96


Multiple plots per figure window (1)

The subplot function is used to create a matrix of plots in a single figure


window.
Syntax:
subplot(nrows,ncols,thisPlot)

Repeat the values of nrows and ncols for all plots in a single figure
window. Increment thisPlot for each plot

NMM: Interactive Computing with Matlab page 97


Multiple plots per figure window (1)

Example:
>> x = linspace(0,2*pi);
>> subplot(2,2,1);
>> plot(x,sin(x)); axis([0 2*pi -1.5 1.5]); title(’sin(x)’);

>> subplot(2,2,2);
>> plot(x,sin(2*x)); axis([0 2*pi -1.5 1.5]); title(’sin(2x)’);

>> subplot(2,2,3);
>> plot(x,sin(3*x)); axis([0 2*pi -1.5 1.5]); title(’sin(3x)’);

>> subplot(2,2,4);
>> plot(x,sin(4*x)); axis([0 2*pi -1.5 1.5]); title(’sin(4x)’);

(See next slide for the plot.)

NMM: Interactive Computing with Matlab page 98


Multiple plots per figure window (2)

sin(x) sin(2x)
1.5 1.5
1 1
0.5 0.5
0 0
-0.5 -0.5
-1 -1
-1.5 -1.5
0 2 4 6 0 2 4 6

sin(3x) sin(4x)
1.5 1.5
1 1
0.5 0.5
0 0
-0.5 -0.5
-1 -1
-1.5 -1.5
0 2 4 6 0 2 4 6

NMM: Interactive Computing with Matlab page 99


Plot Annotation

Name Operation(s) performed


axis Reset axis limits
grid Draw grid lines at the major ticks marks on the x and y axes
gtext Add text to a location determined by a mouse click
legend Create a legend to identify symbols and line types when multiple
curves are drawn on the same plot
text Add text to a specified (x, y) location
xlabel Label the x-axis
ylabel Label the y -axis
title Add a title above the plot

NMM: Interactive Computing with Matlab page 100

You might also like