Transcript ppt

CS100A, Fall 1998
Lecture 20, Tuesday Nov 10
More Matlab
Concepts:
• plotting (cont.)
• 2-D arrays
• Control structures: while, if, for
• Defining new Matlab functions
Readings: As before. Select from:
• Getting Started with Matlab
• Mastering Matlab
• Student Edition of Matlab User’s Guide
CS100A, Fall 1998, Lecture 20
1
Basic Plotting
• If x and y are two arrays with the same
number of elements, plot(x,y) draws a plot
of x (horizontal) vs y (vertical)
x = linspace(0, 4*pi, 250);
y = sin(x);
plot(x,y)
• Normally the graph is scaled so the full
range of x and y values fill the plot. To
have equal spacing on the axes, enter
axis(‘equal’)
after the plot has been drawn (using straight
quote marks).
• You can label the axes and title the graph
after it has been drawn:
xlabel(‘x axis label’)
ylabel(‘y axis label’)
title(‘A Fabulous Graph’)
CS100A, Fall 1998, Lecture 20
2
Plot Options
• The plot command has an optional third
argument that can be used to specify the
line color and style. Examples:
v = -10:0.5:10;
fv = 3*pi*sin(v).^2 - v;
plot(v, fv, ‘g’); % green line
plot(v, fv, ‘b:’); % blue dotted line
plot(v, fv, ‘r+’); % red crosses
plot(v, fv, ‘c--’); % cyan dashed line
• Use help plot to find other possibilities
CS100A, Fall 1998, Lecture 20
3
Multiple Plots
• Normally each new plot is drawn in a blank
window, replacing whatever is there. Use
hold on to retain the previous plot so you
can draw a new one over it. Use hold off to
release the previous plot so the next one
will appear in a blank window. Example:
x = linspace(0, 6*pi, 1000);
y = sin(x);
z = cos(x);
plot(x, y, ‘r’);
hold on
plot(x, z, ‘g’);
CS100A, Fall 1998, Lecture 20
4
2-D Arrays
• Matlab’s basic data structure is a 2-D array
of numbers (1-D arrays are a special case of
this). There are various ways to create 2-D
arrays. Easiest is to list the rows separated
by semicolons:
a = [1 2 3 4; 5 6 7 8; 9 10 11 12]
• Functions are provided to construct arrays
with m rows and n columns initialized in
various ways.
ones(m,n)
% m by n 1’s
zeros(m,n)
% m by n 0’s
rand(m,n)
% m by n random
% numbers in the range
% 0.0 to 1.0.
• If A is a 2-D array, size(A) is a 1-D array
containing the number of rows and columns
in A.
CS100A, Fall 1998, Lecture 20
5
2-D Array Subscripting
• Individual elements of a 2-D array a are
accessed by listing the row and column
numbers in parentheses
a(1,3)
a(3,1)
a(2,2)
• Entire rows and columns can be accessed
using a colon as a “wildcard”
a(2, :)
a(:, 3)
CS100A, Fall 1998, Lecture 20
6
2-D Array Subscripting
• The colon operator can be used to access
arbitrary slices of an array.
a(2:3, 1:2)
% rows 2-3, cols 1-2
a(1:2, 4)
% rows 1-2, col 4
a(1:2, :)
% rows 1-2, all cols
• It can also be used to change the shape of
an array by deleting rows, columns, or submatrices of a matrix.
a(1:2, :) = [] % removes rows 1-2
% from a
CS100A, Fall 1998, Lecture 20
7
Combining and Transposing 2-D arrays
• If A, B, C, and D are arrays,
– [A B] or [A , B] is an array formed by
combining the columns of A and B
with A on the left. A and B must have
the same number of rows.
– [C ; D] is an array formed by stacking
the rows of C above the rows of D. C
and D must have the same number of
columns.
• If A is an array with m rows and n columns,
A’ (A quote-mark) is an array with n rows
and m columns with A’(i,j) = A(j,i). The
result is known as the transpose of A.
CS100A, Fall 1998, Lecture 20
8
Functions and 2-D Arrays
• Functions like sqrt, sin, cos that operate
element-by-element on 1-D arrays work the
same on 2-D arrays.
m = 10 * rand(5,4)
sqrt(sin(m))
• Functions like sum, prod that produce a
scalar result from a 1-D array produce a
1-D array result when applied to a 2-D
array. The function is applied to columns of
the 2-D array.
a = [1 2 3; 4 5 6; 7 8 9; 10 11 12]
sum(a)
• To apply these functions to rows in a 2-D
array, transpose the array with the quote
operator.
sum(a’)
CS100A, Fall 1998, Lecture 20
9
•
•
•
•
Control Structures in Matlab — if
Like most programming languages, Matlab
has loops and conditional statements,
although these are needed far less often
because of the available array operations.
The punctuation differs from Java.
if statement basic form:
if logical expression
statements
end
Example:
if x > y
temp = x;
x = y;
y = temp;
end
Semicolons are optional
CS100A, Fall 1998, Lecture 20
10
Control Structures in Matlab — else
if-else statement basic form:
if logical expression
statements
else
statements
end
Example:
if x > y
temp = x;
x = y;
y = temp;
else
x = y;
end
CS100A, Fall 1998, Lecture 20
11
Control Structures in Matlab — while
while statement basic form:
while logical expression
statements
end
Example:
while k>0
sum = sum + k;
k = k - 1;
end
CS100A, Fall 1998, Lecture 20
12
Control Structures in Matlab — for
• The colon operator (or any array for that
matter) can be used to generate index values
for a loop.
• Example: Create an array with each
element a(i,j) initialized to i+j. We allocate
the array first to avoid array index out-ofbounds errors.
a = zeros(25, 15);
for r = 1 : 25
for c = 1 : 15
a(r,c) = r + c;
end
end
• But — In Matlab there are often ways to do
matrix operations without explicit loops.
Don’t write loops if you don’t need them.
CS100A, Fall 1998, Lecture 20
13
Creating New Functions — .m Files
• New functions can be defined by storing the
commands to compute them in a file with a
name that exactly matches the function
name followed by .m .
• Function definition syntax:
function [output vars ] = function_name ( input vars )
• Example: File sqr.m.
function [result] = sqr(x);
% yield the square of the values in x
result = x .* x;
• All variables are local to the function.
• Comments that immediately follow the
function definition line are used by help and
lookfor
• Functions may be applied to any Matlab
data and will be applied element-byelement automatically if appropriate.
CS100A, Fall 1998, Lecture 20
14